【发布时间】:2019-01-14 19:24:17
【问题描述】:
我正在开发一些 Web API,并负责使用 ASP.NET Identity 2.0 向一些端点添加基于角色的授权。
我创建了一个基于 API 的管理结构来管理用户和角色,并且在尝试使用 OAUTH Bearer 令牌实现授权/身份验证时遇到了问题。
(注意我读到 JWT 更好用,并且使提供用户数据更简单,但要求的是普通 OAUTH)
至于这里的代码是我目前所拥有的,包括症结所在:
Startup.cs:
private static void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
// Configure the db context, user manager and role manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
// Create the options for the token authorization
var oauthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oauthAuthorizationServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
SimpleAuthorizationServerProvider.cs:
public sealed class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// We are not validating clients at this point, simply "resource owners" i.e. user / pass combos
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var repo = new AuthorizationRepository())
{
var user = repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
// How do you pull the user data (including roles) from the database here, and place into a claim for API consumption??
}
}
我在网上找到的内容如下,但这只会为用户创建一个默认角色(或角色列表):
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("sub", context.UserName));
context.Validated(identity);
上面的代码是个问题,因为它会验证用户,然后在生成的令牌中为每个用户分配管理员角色!
任何帮助将不胜感激,并感谢您的帮助!
【问题讨论】:
-
你想使用OWIN注册的ApplicationManager,并用它来创建默认的
ClaimsIdentity。var mgr = context.OwinContext.GetUserManager<ApplicationUserManager>();然后var identity = await mgr.CreateIdentityAsync(user, context.Options.AuthenticationType); -
+1 对于这个答案@BrendanGreen,希望我能将此标记为已解决的答案!非常感谢您的帮助,效果很好!一直在互联网上寻找有关此问题的答案!干杯伙伴!
-
添加为答案,以便您接受:-)
-
太棒了,再次感谢@BrendanGreen!
标签: c# asp.net asp.net-identity asp.net-roles