用于Mongodb数据存储的asp.net核心中基于令牌的简单身份validation/授权
我需要实现非常简单的auth mechanizm,基本上有2个角色: Owners
和Users
。 而且我认为拥有Enum就足够了。 应用程序本身是SPA,通过Asp.net核心实现webapi。 我看到了文章 – 如何使用EF Identity实现它,但是他们的模型看起来比我实际需要的复杂得多,并且EF面向SQL db,我使用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
Microsoft.AspNetCore.Authentication.AuthenticationHandler
然后将此中间件添加到您的启动类。
代码示例:
public class TokenOptions : AuthenticationOptions { public TokenOptions() : base() { AuthenticationScheme = "Bearer"; AutomaticAuthenticate = true; } } public class AuthMiddleware : AuthenticationMiddleware { protected override AuthenticationHandler CreateHandler() { return new AuthHandler(new TokenService()); } public AuthMiddleware(RequestDelegate next, IOptions options, ILoggerFactory loggerFactory, UrlEncoder encoder) : base(next, options, loggerFactory, encoder) { } } public class AuthHandler : AuthenticationHandler { private ITokenService _tokenService; public AuthHandler(ITokenService tokenService) { _tokenService = tokenService; } protected override async Task 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(); 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代码只是为了说明想法。 当然,您需要实现自己的处理程序。
您可以使用自定义middleware
来validation用户身份并设置claims
(名称,角色等)。
我将尝试编写一个简单的middleware
:
首先创建一个middlware
class
:
public class CustomMiddleware { private readonly RequestDelegate _next; private readonly UserRepository _userRepository; public CustomMiddleware(RequestDelegate next, UserRepository userRepository) { _next = next; _userRepository = userRepository; } public async Task Invoke(HttpContext context) { string token = context.Request.Headers["Token"]; var user = _userRepository.Get(token); ClaimsIdentity claimsIdentity = new ClaimsIdentity("Custom"); var claims = new List(); claims.Add(new Claim(ClaimTypes.Name, "admin")); claims.Add(new Claim(ClaimTypes.NameIdentifier, "admin")); foreach(var role in user.Roles) { claims.Add(ClaimTypes.Role, role); } ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity); context.User = claimsPrincipal; await _next(context); } }
然后在Startup.cs
使用这样的middleware
:
public void Configure(IApplicationBuilder app) { app.UseMiddleware(); ... }
最后使用Authorize
属性:
上述就是C#学习教程:用于Mongodb数据存储的asp.net核心中基于令牌的简单身份validation/授权分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
[Authorize(Roles = "Users")] public IActionResult Index() { }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/957279.html