【问题标题】:ASP.NET Web API Authorization with Postman使用 Postman 进行 ASP.NET Web API 授权
【发布时间】:2026-01-16 14:15:02
【问题描述】:

我创建了一个 ASP.NET Web API 并将 Authorize 属性应用于 API 控制器。现在,我想使用 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

我正在使用这个高级邮递员休息客户端http://prntscr.com/c8xafd

如何在 Postman 中通过授权?

【问题讨论】:

    标签: c# asp.net-web-api postman


    【解决方案1】:

    编辑 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 中具有标识的默认配置。 我可以争辩为什么它不是安全的好选择,但这不是重点。

    你可以在“邮递员”中使用它,但这很棘手 我就是这样做的:

    1. 通过您的登录页面发出请求:

    1. 获取表单中的防伪令牌:

    1. 在登录页面上使用此帖子参数以数据形式发出帖子请求:

    现在您的邮递员获得了身份验证 cookie,您可以使用 [authorize] 标签请求 web api

    编辑

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

    • 进入标题表单
    • 添加HTTP头“授权”
    • 点击编辑按钮等瞧;)

    screen shot

    上一个答案已删除

    【讨论】:

    • 这是用于基本身份验证,具体取决于您的身份验证机制
    • 我正在使用身份。我使用了上述方法,但仍然得到像这样的身份验证错误prntscr.com/c908zb
    • 我添加了一种方法来进行 cookie 身份验证。每次您的身份验证会话关闭时,您都必须这样做。如果您必须通过电话应用程序使用 Web api,我建议您切换到基于令牌的身份验证。在手机应用程序上维护 cookie 是一团糟;)
    • 非常感谢您提供如此详细的答案。有效。你摇滚!
    • 谢谢!有人帮助了我,所以现在我尽我所能支付我的欠款:)
    【解决方案2】:

    除了 Mathieu 发布的答案之外,我还必须为邮递员(https://www.getpostman.com/docs/interceptor_cookieshttps://www.getpostman.com/docs/capture)安装拦截器扩展来捕获 cookie。之后就成功了。

    【讨论】:

      【解决方案3】:

      对于 Postman Windows 应用 4.6.0:

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

      【讨论】: