OAuth令牌承载额外的用户信息

时间:2015-04-17 07:48:20

标签: oauth asp.net-web-api2

我使用的是使用OAuth Bearer令牌保护的Web API。获取令牌时,我想向用户发送额外信息,因此我按照this thread尝试了以下内容:

CustomOAuthProvider.cs:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    // Other stuff, cut off for brevity

    var user = await userManager.FindAsync(context.UserName, context.Password);

    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
    oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
    oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

    var ticket = new AuthenticationTicket(oAuthIdentity, this.CreateProperties(user.UserName, oAuthIdentity));

    context.Validated(ticket);
}

private AuthenticationProperties CreateProperties(string userName, ClaimsIdentity oAuthIdentity)
{
    var data = new Dictionary<string, string>
    {
        { "username", userName },
        { "roles", JsonConvert.SerializeObject(oAuthIdentity.Claims.Where(c=> c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray()) }
    };
    return new AuthenticationProperties(data);
}

但是返回的对象总是如下:

{
    access_token: "theTokenHash"
    expires_in: 86399
    token_type: "bearer"
}

这是我的Startup.cs:

public void Configuration(IAppBuilder app)
{
    // AutoMapper
    AutoMapperConfig.RegisterMappings();

    var httpConfig = new HttpConfiguration();

    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

    ConfigureOAuthTokenGeneration(app);
    ConfigureOAuthTokenConsumption(app);
    ConfigureWebApi(httpConfig);

    WebApiConfig.Register(httpConfig);
    AutofacConfig.Register(httpConfig);

    app.UseWebApi(httpConfig);

    httpConfig.EnsureInitialized();
}

private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
    // Configure the db context and user manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

    var OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        //For Dev enviroment only (on production should be AllowInsecureHttp = false)
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/oauth/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new CustomOAuthProvider(),
        AccessTokenFormat = new CustomJwtFormat("http://localhost:59822")
    };

    // OAuth 2.0 Bearer Access Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

哇,没关系,我挖掘了链接答案中给出的完整例子。似乎添加额外的字段是不够的。您仍然必须通过覆盖TokenEndpoint函数来自行将参数添加到上下文中:

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);
}
相关问题