使用Web Api中的Postman授权属性身份验证 [英] Authorize Attribute Authentication with Postman in Web Api

查看:545
本文介绍了使用Web Api中的Postman授权属性身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RESTful服务,并发现Postman是GET,POST和测试API的最佳插件之一。



我发现基本身份验证,无身份验证,邮递员中的摘要身份验证,OAuth,AWS。如何测试授权控制器和方法。



我知道Authorize属性检查 user.Identity.IsAuthenticated



我不确定如何使用邮递员在具有以下特定角色的控制器和方法中通过授权

  [ Authorize(角色=管理员,超级用户)] 

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

这是我的启动文件

 公共静态OAuthAuthorizationServerOptions OAuthOptions {get;私人套装; } 

公共静态字符串PublicClientId {get;私人套装; }

//有关配置身份验证的更多信息,请访问http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
//将数据库上下文和用户管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext< ApplicationUserManager>(ApplicationUserManager.Create);

//使应用程序能够使用cookie来存储已登录用户
//的信息,并使用cookie来临时存储有关使用第三方登录名登录的用户的信息提供者
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

//为基于OAuth的流配置应用程序
PublicClientId = self;
OAuthOptions =新的OAuthAuthorizationServerOptions
{
TokenEndpointPath =新的PathString( / Token),
Provider =新的ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath =新的PathString( / api / Account / ExternalLogin),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
//在生产模式下设置AllowInsecureHttp = false
AllowInsecureHttp = true
};

//使应用程序能够使用承载令牌来认证用户
应用程序。UseOAuthBearerTokens(OAuthOptions);
}


解决方案

1。在网络api中启用CORS



在Startup.cs配置方法中将以下内容附加到IAppBuilder(如果遇到麻烦,请在此处阅读更多信息



3。使用令牌并从Web api获取数据



注意:令牌响应包含access_token(令牌)和token_type(承载)。在请求中使用时,请在Authorization http标头的值之间添加一个空格。认证服务器将解析令牌并设置用户。请求在请求的控制器中击中[Authorize]属性之前的身份





此外,请确保ApplicationOAuthProvider向令牌中添加包含当前角色的Claimidentity。否则,该请求将被拒绝。一种测试方法是只使用[Authorize]属性而不使用角色,然后查看邮递员是否可以访问控制器


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);         
    }

解决方案

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

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

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

这篇关于使用Web Api中的Postman授权属性身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆