Postman的ASP.NET Web API授权

Asi*_*eed 6 c# asp.net-web-api postman

我创建了一个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();
        }
Run Code Online (Sandbox Code Playgroud)

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

我正在使用这个先进的Postman休息客户端http://prntscr.com/c8xafd

我如何通过Postman授权?

Mat*_*ieu 12

编辑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))
                }
            });    
Run Code Online (Sandbox Code Playgroud)

这是Visual Studio中具有标识的默认配置.我可以说为什么它不是一个安全的好选择,但这不是重点.

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

  1. 通过您的登录页面提出请求: 在此输入图像描述
  2. 获取表单中的防伪标记: 在此输入图像描述
  3. 在登录页面上发布帖子请求,并以数据形式提供此帖子参数: 在此输入图像描述

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

编辑

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

  • 进入标题表格
  • 添加HTTP标头"授权"
  • 点击编辑按钮etvoilà;)

屏幕截图

先前的答案删除

  • 我添加了一个方法来进行 cookie 身份验证。每次您的身份验证会话失败时,您都必须这样做。例如,如果您必须从电话应用程序使用 Web api,我建议您切换到基于令牌的身份验证。在手机应用程序上维护 cookie 是一团糟;) (2认同)