【问题标题】:Pass back parameters in ASP.NET Web API GrantResourceOwnerCredentials在 ASP.NET Web API GrantResourceOwnerCredentials 中传回参数
【发布时间】:2014-08-11 09:06:37
【问题描述】:

我试图在用户登录后从 ASP.NET Web API 传回一些参数。

我的工作基于这个不错的教程: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

例如,我可以在演示页面上看到他发回用户名。

我创建了自己的提供程序,它继承自 OAuthAuthorizationServerProvider 这就是我所做的:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{ 
    ....

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    identity.AddClaim(new Claim("role", user.Role));

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        { 
            "userName", user.UserName
        },
        { 
            "role", user.Role
        }
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}

这就是我连接它的方式:

var OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
var OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = new SimpleAuthorizationServerProvider()
};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);

据我了解,AuthenticationProperties 字典应该在 JSON 响应中传回给客户端。但由于某种原因,我没有得到我的附加参数。这是我得到的:

{"access_token":"G4S1PXdNbtAHLFBo......","token_type":"bearer","expires_in":86399}

我花了很多时间试图弄清楚这一点,有人能看出我失踪了吗?

【问题讨论】:

    标签: asp.net-web-api owin


    【解决方案1】:

    我发现了我的问题。好像我误解了属性字典。

    我添加了这个方法:

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
    
        return Task.FromResult<object>(null);
    }
    

    它基本上将字典中的条目添加到响应中。我的错误是假设这会自动为我完成。

    【讨论】:

    • 我不敢相信花了多长时间才弄清楚这一点。我看到了大量添加属性的示例,但这是我第一次看到需要重写此方法以在响应中获取它们。
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多