在ASP.NET Core中针对Mongodb数据存储区的基于简单令牌的身份验证/授权 [英] Simple token based authentication/authorization in asp.net core for Mongodb datastore

查看:279
本文介绍了在ASP.NET Core中针对Mongodb数据存储区的基于简单令牌的身份验证/授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现基本上具有两个角色的非常简单的身份验证机制:OwnersUsers.我认为拥有Enum就足够了.应用本身就是SPA,并通过Asp.net核心实现了webapi.我看到了一篇文章-如何使用EF身份来实现它,但是他们的模型看起来比我实际需要的要复杂得多,并且面向SQL db的EF以及我使用mongo.因此,我的用户将类似于:

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. App itself is SPA with webapi implemented via Asp.net core. I saw article - how to implement it using EF Identity, but their models looks much more complex than I actually need and EF oriented to SQL db, and I using mongo. So my user will looks something like:

class UserModel{
    Id, 
    Token, 
    Roles: ["Owners", "Users"],
    ...
}

那么我需要实现哪些接口并将其添加到DI中才能使用 [Authorize][Authorize(Roles="Users")]属性,它们基于我在标头中发送的令牌正确工作吗?

So what interfaces I need to implement and add to DI to be able use [Authorize] and [Authorize(Roles="Users")] attribute and they worked correctly based on token I send in header?

推荐答案

让我澄清一下@Adem的答案.您需要以特定方式实现自定义中间件.要实现此目的,需要实现3个抽象类(答案对于asp.net core rc2 btw是正确的):

Let me clarify a little @Adem's answer. You need to to implement custom middleware in specific way. There is 3 abstract classes that need to be implemented to implementing this (answer is correct for asp.net core rc2btw):

Microsoft.AspNetCore.Builder.AuthenticationOptions Microsoft.AspNetCore.Authentication.AuthenticationMiddleware<TOptions> Microsoft.AspNetCore.Authentication.AuthenticationHandler<TOptions>

,然后将此中间件添加到您的启动类中.

and then add this middleware to your startup class.

代码示例:

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;
    }
}`

p.s.该代码仅用于说明想法.您当然需要实现自己的处理程序.

这篇关于在ASP.NET Core中针对Mongodb数据存储区的基于简单令牌的身份验证/授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆