I want to build my own authentication process using Claims based authentication in my ASP.net MVC project. I want to be able to use the Authorize attribute (including roles), for example [Authorize(Roles="admin")]
and [Authorize(Roles="Frontenduser")]
as I will have multiple types of users.
I don't want to use ASP.net identity as it does a bit too much than what I need. I also need totally different data to be stored for the different types of users.
I know I can inherit from the AuthorizeAttribute class but I am unsure how it all works with claims. So firstly, can anyone recommend a good package to use claims based authentication and secondly, how do I stop the Authorize attribute working with ASP.net Identity and get it to work with my custom claims based authentication? I have had a look at other questions and other solutions across the web but I cannot find a suitable explanation or solution.
You can Use Policy based Authorization. Identity is Authentication and different than authorization. For this you can make a policy in your startup class. This is an example of mine in the configure services. If you dont need Identity you can use JWT bearer tokens and just make a policy. get these packages from nuget:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public void ConfigureServices(IServiceCollection services)
{
//new policy makes [Authorize (Policy = "Your custom Policy")] availible by claims This is what you put on controllers
services.AddAuthorization((options) => {
options.AddPolicy("Your custom Policy", policybuilder =>
{
policybuilder.RequireAuthenticatedUser();
policybuilder.RequireClaim("role", "PayingUserExampleProperty");
});
});
in your configure
add
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
...
Good read into this:
https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.