简体   繁体   中英

ASP .NET 4.7 MVC Authentication and Authorization Identity

I am creating a MVC web API. The endpoints will be hidden behind authentication via a custom token. However, there will also be scoping on certain individual endpoints, access to admins etc. I am trying to figure out how to create a user, or, when the user is authenticated to set him so in the authorization filter I can verify if he is an admin, or if he has read access to that particular resource at that endpoint.

What is the best way to do this, can I set the identity principal in the authentication filter, or is there a better way ?

you can used the [Authorize] Attribute my friend ,

first : add the AuthorizeAttribute filter to the global filter list:

 public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new AuthorizeAttribute());
    }

second : to secure your controller ,add the filter as an attribute to the controller

// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
    public HttpResponseMessage Get(int id) { ... }
    public HttpResponseMessage Post() { ... }
}

three to secure your action , add the attribute to the action method:

public class ValuesController : ApiController
{
    public HttpResponseMessage Get() { ... }

    // Require authorization for a specific action.
    [Authorize]
    public HttpResponseMessage Post() { ... }
}

i advise you to visit this 2 link can help you more:

Authentication and Authorization in ASP.NET Web API
MVC Web API: Authorization & Authentication

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM