在您的 Startup 类上,当配置 OAuthAuthorizationServerOptions 时,在 Provider 属性上您应该有一个从 OAuthAuthorizationServerProvider 继承的自定义类。在下面的示例中,CustomAuthorizationServerProvider 类:
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomAuthorizationServerProvider()
};
这是 CustomAuthorizationServerProvider 的代码,您必须在其中覆盖 GrantResourceOwnerCredentials:
public class CustomAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
...
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
if (allowedOrigin == null) allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
IdentityUser user;
using (AuthRepository repository = new AuthRepository())
{
user = await repository.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect");
return;
}
}
UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new AuthDBContext()));
ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
AuthenticationProperties properties = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", context.ClientId ?? string.Empty
},
{
"userName", context.UserName
},
{
"roles",String.Join(",", (IEnumerable<IdentityUserRole>) user.Roles.ToArray())
}
});
AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
}
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);
}
}
注意:AuthDBContext 与您声明 OnModelCreating 方法的类相同。
因此,查看上面的代码,您将检查用户角色是否已插入到 AuthenticationProperties 字典中
{
"roles",String.Join(",", (IEnumerable<IdentityUserRole>) user.Roles.ToArray())
}
然后将它们与当前用户的 ClaimsIdentity 对象一起插入到工单中。
AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
一旦您解决了这个问题,您只需在您的操作和/或控制器中添加 [Authorize] 属性,如下所示:
[Authorize(Roles = "Admin")]
或者签入你的控制器动作等价物:
ActionContext.RequestContext.Principal.IsInRole("Admin")