使用 web api bearer token base authentication 生成令牌时如何设置一些用户数据
How to set some user data when token generate using web api bearer token base authentication
当token生成的时候我自己的条件是流动的,我想获取登录用户的一些数据。
我已经完成访问令牌生成
这是我的 Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);
var myProvider = new MyAuthorizationServerProvider();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = myProvider
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
}
MyAuthorizationServerProvider class
public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private readonly ReviewDbContext db;
public MyAuthorizationServerProvider()
{
db = new ReviewDbContext();
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
if (admin != null && user == null)
{
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("UserName", admin.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
context.Validated(identity);
}
else if (user != null)
{
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("UserName", user.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
context.Validated(identity);
}
else
{
context.SetError("Invalid_grant", "Provided username & password is incorrect");
return;
}
}
}
AuthorizeAttribute class
public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(actionContext);
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
邮递员
我的预期输出如下:
我在哪里设置我想要的用户数据和用户生成令牌。
如何实现?
您正在向您的令牌添加声明,因此为了访问它们,您需要对令牌进行解码。但是,如果您希望您的额外数据位于令牌之外(例如您绘制的图像),您可以将它们作为不同的属性添加到登录响应对象中:
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"UserName", "AA"
},
{
"UserId" , "1"
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
此外,您需要在MyAuthorizationServerProvider
中添加以下方法:
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);
}
当token生成的时候我自己的条件是流动的,我想获取登录用户的一些数据。
我已经完成访问令牌生成
这是我的 Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);
var myProvider = new MyAuthorizationServerProvider();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = myProvider
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
}
MyAuthorizationServerProvider class
public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private readonly ReviewDbContext db;
public MyAuthorizationServerProvider()
{
db = new ReviewDbContext();
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
if (admin != null && user == null)
{
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("UserName", admin.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
context.Validated(identity);
}
else if (user != null)
{
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("UserName", user.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
context.Validated(identity);
}
else
{
context.SetError("Invalid_grant", "Provided username & password is incorrect");
return;
}
}
}
AuthorizeAttribute class
public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(actionContext);
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
邮递员
您正在向您的令牌添加声明,因此为了访问它们,您需要对令牌进行解码。但是,如果您希望您的额外数据位于令牌之外(例如您绘制的图像),您可以将它们作为不同的属性添加到登录响应对象中:
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"UserName", "AA"
},
{
"UserId" , "1"
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
此外,您需要在MyAuthorizationServerProvider
中添加以下方法:
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);
}