首页 文章

ASP.NET 邮递员的 Web API 授权

提问于
浏览
6

我创建了一个 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 授权?

3 回答

  • 11

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

    你可以在“邮递员”中使用它,但这很难处理我是这样做的:

    • 通过您的登录页面提出请求:
      在此输入图像描述

    • 获取表单中的防伪标记:
      在此输入图像描述

    • 在登录页面上发布帖子请求,并以数据形式提供此帖子参数:
      在此输入图像描述

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

    编辑

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

    • 进入标题表格

    • 添加 HTTP 标头“授权”

    • 点击编辑按钮 etvoilà;)

    屏幕截图

    以前的答案已删除

  • 2

    对于 Postman Windows App 4.6.0:

    • 从您的请求集中选择您的请求

    • 转到“授权”选项卡

    • 选择合适的“类型”,e.g. “基本认证”

    • 输入“用户名”和“密码”

    • 点击“更新请求”

  • 0

    除了 Mathieu 发布的答案之外,我还必须为 postman(https://www.getpostman.com/docs/interceptor_cookieshttps://www.getpostman.com/docs/capture)安装拦截器扩展来捕获 cookie。之后它起作用了。

相关问题