OAuth令牌承载额外用户信息
我正在使用由OAuth承载令牌保护的Web API。在获取令牌时,我希望向用户发送额外信息,因此我根据尝试了以下操作: CustomOAuthProvider.cs:OAuth令牌承载额外用户信息,oauth,asp.net-web-api2,Oauth,Asp.net Web Api2,我正在使用由OAuth承载令牌保护的Web API。在获取令牌时,我希望向用户发送额外信息,因此我根据尝试了以下操作: CustomOAuthProvider.cs: public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // Other stuff, cut off for brevity var user =
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);
}
这是我的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());
}
public void配置(IAppBuilder应用程序)
{
//汽车制造商
AutoMapperConfig.RegisterMappings();
var httpConfig=new HttpConfiguration();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
配置OAuthTokenGeneration(应用程序);
配置OAuthTokenConsumption(应用程序);
配置webapi(httpConfig);
WebApiConfig.Register(httpConfig);
AutofacConfig.Register(httpConfig);
app.UseWebApi(httpConfig);
httpConfig.EnsureInitialized();
}
私有void配置OAuthTokenGeneration(IAppBuilder应用程序)
{
//将db上下文和用户管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationRoleManager.Create);
var OAuthServerOptions=新的OAuthAuthorizationServerOptions()
{
//仅适用于开发环境(在生产环境中应为AllowInsecureHttp=false)
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/oauth/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
Provider=新的CustomOAuthProvider(),
AccessTokenFormat=新的CustomJwtFormat(“http://localhost:59822")
};
//OAuth 2.0承载访问令牌生成
使用OAuthAuthorizationServer(OAuthServerOptions);
使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions());
}
我做错了什么?哇,没关系,我深入研究了链接答案中给出的完整示例。似乎添加额外的字段是不够的。您仍然需要通过重写
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);
}
public覆盖任务令牌端点(OAuthTokenEndpointContext)
{
foreach(context.Properties.Dictionary中的KeyValuePair属性)
{
AdditionalResponseParameters.Add(property.Key,property.Value);
}
返回Task.FromResult(空);
}
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);
}