在 Web Api 中使用 Postman 授权属性认证

Authorize Attribute Authentication with Postman in Web Api(在 Web Api 中使用 Postman 授权属性认证)
本文介绍了在 Web Api 中使用 Postman 授权属性认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在 postman 中找到了 Basic Auth、No Auth、DIgest Auth、OAuth、AWS.如何测试授权控制器和方法.

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

我不确定如何使用 Postman 在控制器和具有特定角色的方法中传递授权,如下所示

[Authorize(Roles = "Admin, Super User")]公共 ActionResult AdministratorsOnly(){返回视图();}

这是我的启动文件

 public static OAuthAuthorizationServerOptions OAuthOptions { get;私人套装;}公共静态字符串 PublicClientId { 获取;私人套装;}//有关配置身份验证的更多信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864公共无效 ConfigureAuth(IAppBuilder 应用程序){//将数据库上下文和用户管理器配置为每个请求使用单个实例app.CreatePerOwinContext(ApplicationDbContext.Create);app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);//使应用程序能够使用 cookie 来存储登录用户的信息//并使用 cookie 临时存储有关使用第三方登录提供程序登录的用户的信息app.UseCookieAuthentication(new CookieAuthenticationOptions());app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);//为基于 OAuth 的流配置应用程序PublicClientId = "自我";OAuthOptions = 新的 OAuthAuthorizationServerOptions{TokenEndpointPath = new PathString("/Token"),Provider = new ApplicationOAuthProvider(PublicClientId),AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),//在生产模式下设置 AllowInsecureHttp = falseAllowInsecureHttp = true};//使应用程序能够使用不记名令牌对用户进行身份验证app.UseOAuthBearerTokens(OAuthOptions);}

解决方案

1.在 web api 中启用 CORS

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

3.使用令牌并从 web api 获取数据

注意:令牌响应包含作为令牌的 access_token 和作为承载的令牌类型.在请求中使用时,在 Authorization http 标头的值之间添加一个空格.身份验证服务器将解析令牌并在请求命中所请求控制器中的 [Authorize] 属性之前设置 user.Identity

此外,请确保 ApplicationOAuthProvider 将包含当前角色的声明身份添加到令牌中.否则请求将被拒绝.测试它的一种方法是只使用没有角色的 [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 授权属性认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)