我需要实现基本上具有2个角色的非常简单的身份验证机制:Owners
和Users
。我认为拥有Enum就足够了。应用本身就是SPA,并通过Asp.net核心实现了webapi。我看到了一篇文章-如何使用EF身份来实现它,但是他们的模型看起来比我实际需要的要复杂得多,并且面向SQL db的EF以及我使用mongo。因此,我的用户将如下所示:
class UserModel{
Id,
Token,
Roles: ["Owners", "Users"],
...
}
那么,我需要实现哪些接口并将其添加到DI才能使用[Authorize]
和分配[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;
}
}`
ps该代码仅用于说明想法。当然,您将需要实现自己的处理程序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句