Authorize Attribute Authentication with Postman in

2019-06-01 09:22发布

I am working with RESTful services and find Postman as one of the best plugin to GET, POST and test the API's.

I find Basic Auth, No Auth, DIgest Auth, OAuth, AWS in postman. How do I test the Authorize Controller and methods.

I am aware that Authorize attribute checks user.Identity.IsAuthenticated

I am not sure on how to pass authorize in controller and methods with specific roles like below using Postman

[Authorize(Roles = "Admin, Super User")]

public ActionResult AdministratorsOnly()
{
    return View();
}

Here is my Startup file

  public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);         
    }

2条回答
可以哭但决不认输i
2楼-- · 2019-06-01 09:53

1. Enable CORS in the web api

Attach the following to the IAppBuilder in the Startup.cs Configuration method (If you face trouble, read more here How to make CORS Authentication in WebAPI 2?)

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

Nuget package here

2. Get a token via Postman

enter image description here

3. Use the token and get data from the web api

Note: The token response contains of access_token which is the token and the token_type which is bearer. When used in request, add them with a space between in the value of the Authorization http header. The auth server will parse the token and set the user.Identity before the request hits the [Authorize] attribute in the requested controller

enter image description here

Also, make sure that the ApplicationOAuthProvider adds the claimidentity that contians the current role/s to the token. Else the request will be denied. One way to test it is to just use [Authorize] attribute without roles and see if postman can access the controller then

查看更多
The star\"
3楼-- · 2019-06-01 10:02

it looks like you are using windows identity provider and using OAuth 2.0 (default for web api 2 template). And also you don't send roles in using postman. Authorization is handled by the framework based on the user claim.

Explanation

When you authenticate with your usename and password to the /Token endpoint, you will be issued with a bearer token and a claim, which holds you identity information including your roles (more like your passport/Id). You will use you bearer token to access authorized resources and you will be granted or denied based on you role associated with it.

How does it know ?

In the database the asp.net identity has automatically created the tables needed for users, roles, externalLogin etc... with the prefix aspnet, when you first launched the application. What you need to do is create a user, create the roles and assign the user to the roles with the aspnet identity provide. Then decorate your resource ends with the authorize attribute and issue a request with postman with only the bearer token( the ones you get when you successfully login to the /token endpoint)

You can refer here to for further explanation.

查看更多
登录 后发表回答