Simple token based authentication/authorization in asp.net core for Mongodb datastore

前端 未结 2 443
南笙
南笙 2020-12-01 17:20

I need to implement pretty simple auth mechanizm with basically 2 roles: Owners and Users. And I think that having Enum for that will be enough. Ap

2条回答
  •  情歌与酒
    2020-12-01 17:46

    You can use custom middleware to authenticate user and set claims(name, roles etc.).

    I will try to write a simple middleware:

    First create a 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);
        }
    }
    

    Then use middleware in Startup.cs like this:

       public void Configure(IApplicationBuilder app)
        {
            app.UseMiddleware();
            ...
        }
    

    Finally use Authorize attribute:

    [Authorize(Roles = "Users")]
    public IActionResult Index()
    {
    } 
    

提交回复
热议问题