我需要实现非常简单的身份验证机制,基本上有两个角色:Owners
and Users
。我认为拥有 Enum 就足够了。应用程序本身是SPA,通过Asp.net core实现webapi。我看到文章 - 如何使用 EF Identity 实现它,但他们的模型看起来比我实际需要的复杂得多并且 EF 面向 SQL db,而我使用 mongo。所以我的用户看起来像这样:
class UserModel{
Id,
Token,
Roles: ["Owners", "Users"],
...
}
那么我需要实现哪些接口并将其添加到 DI 才能使用[Authorize]
and [Authorize(Roles="Users")]
属性并且它们根据我在标头中发送的令牌正常工作?
让我澄清一下@Adem 的答案。您需要以特定方式实现自定义中间件。有 3 个抽象类需要实现来实现这个(答案是正确的)asp.net core rc2
btw):
Microsoft.AspNetCore.Builder.AuthenticationOptions
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware<TOptions>
Microsoft.AspNetCore.Authentication.AuthenticationHandler<TOptions>
然后将此中间件添加到您的启动类中。
代码示例:
public class TokenOptions : AuthenticationOptions
{
public TokenOptions() : base()
{
AuthenticationScheme = "Bearer";
AutomaticAuthenticate = true;
}
}
public class AuthMiddleware : AuthenticationMiddleware<TokenOptions>
{
protected override AuthenticationHandler<TokenOptions> CreateHandler()
{
return new AuthHandler(new TokenService());
}
public AuthMiddleware(RequestDelegate next, IOptions<TokenOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder) : base(next, options, loggerFactory, encoder)
{
}
}
public class AuthHandler : AuthenticationHandler<TokenOptions>
{
private ITokenService _tokenService;
public AuthHandler(ITokenService tokenService)
{
_tokenService = tokenService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string token = null;
AuthenticateResult result = null;
string token = Helper.GetTokenFromHEader(Request.Headers["Authorization"]);
// If no token found, no further work possible
if (string.IsNullOrEmpty(token))
{
result = AuthenticateResult.Skip();
}
else
{
bool isValid = await _tokenService.IsValidAsync(token);
if (isValid)
{
//assigning fake identity, just for illustration
ClaimsIdentity claimsIdentity = new ClaimsIdentity("Custom");
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "admin"));
claims.Add(new Claim(ClaimTypes.NameIdentifier, "admin"));
claims.Add(new Claim(ClaimTypes.Role, "admin"));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
result =
AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal,
new AuthenticationProperties(), Options.AuthenticationScheme));
}
else
{
result = AuthenticateResult.Skip();
}
}
return result;
}
}`
附注该代码仅用于说明想法。当然,您需要实现自己的处理程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)