使用Postman进行ASP.NET Web API授权

13

我创建了一个 ASP.NET Web API 并在API控制器上应用了Authorize属性。现在,我想使用Postman进行测试,但是我遇到了授权错误。

控制器代码如下:

[Authorize]
[HttpPost]
public IHttpActionResult Attend([FromBody] int gigId)
{
    var attendance = new Attdendance
    {
        GigId =  gigId,
        AttendeeId = User.Identity.GetUserId()
    };

    _context.Attdendances.Add(attendance);
    _context.SaveChanges();
    return Ok();
}

我的请求看起来像这样 http://prntscr.com/c8wz0b

我正在使用这个高级Postman REST客户端 http://prntscr.com/c8xafd

如何在Postman中通过授权?


3个回答

17

编辑于23/08/2016 我假设你正在进行基于cookie的身份验证

// 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
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

这是Visual Studio中默认的身份验证配置。 我可以解释为什么它不是安全的好选择,但那不是重点。

你可以在“Postman”中使用它,但这有点棘手, 以下是我的做法:

  1. 通过登录页面进行请求:

enter image description here

  1. 获取表单中的防伪标记:

enter image description here

  1. 使用此帖子参数在数据形式中对登录页面进行POST请求:

enter image description here

现在你的postman获得了认证Cookie,你可以使用[authorize]标签请求Web API。

编辑

对于工具,您必须添加授权标头。

  • 进入Headers表单
  • 添加HTTP头“authorization”
  • 点击编辑按钮,就可以啦 ;)

屏幕截图

以前的答案已删除。


这是用于基本认证的,之后取决于您的身份验证机制。 - Mathieu
我正在使用Identity。我使用了上述方法,但仍然遇到身份验证错误,如此http://prntscr.com/c908zb。 - Asif Hameed
2
我添加了一个方法来支持cookie身份验证。每当您的身份验证会话失效时,您都需要这样做。如果您必须从手机应用程序使用Web API,则建议您切换到基于令牌的身份验证。在手机应用程序上维护cookie非常麻烦 ;) - Mathieu
非常感谢您提供如此详细的答案。它起作用了。你太棒了! - Asif Hameed
谢谢!有人帮了我,现在我尽力回报 :) - Mathieu

4

对于Postman Windows App 4.6.0:

  1. 从请求集合中选择您的请求
  2. 转到“授权”选项卡
  3. 选择适当的“类型”,例如“基本身份验证”
  4. 输入“用户名”和“密码”
  5. 单击“更新请求”

抱歉,我正在使用另一个Postman(https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo)。 - Asif Hameed
不要在设置中更改。http://prntscr.com/c8xorb 我正在使用高级的Postman REST客户端,而不是Postman Windows App 4.6.0。 - Asif Hameed
抱歉,我不熟悉Advanced REST client。但是看起来你可以设置自定义标头。也许你可以手动设置“Authorization”标头。另外,查看一下如何正确发送基本身份验证的授权标头,其中建议在URL中包括用户名和密码。 - Georg Patscheider

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接