Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
silent_coder Avatar asked May 23 '16 17:05

silent_coder


People also ask

Can you use MongoDB with ASP.NET Core?

Driver package allows . NET Core to connect to the MongoDB database. ou'll use the Microsoft. AspNetCore.


1 Answers

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<Claim>();
        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<CustomMiddleware>();
        ...
    }

Finally use Authorize attribute:

[Authorize(Roles = "Users")]
public IActionResult Index()
{
} 
like image 108
adem caglin Avatar answered Oct 09 '22 20:10

adem caglin