Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

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

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"],
    ...
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Code example:

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. The code is just for illustration of idea. You will need to implement your own handler of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...