承载错误= Invalid_token 401未经授权

时间:2016-12-22 17:26:40

标签: asp.net-web-api2 asp.net-core-mvc postman bearer-token asp.net-core-1.1

 var identity = new GenericIdentity(user.Username, "Token");
            var claims = new List<Claim>();
            claims.AddRange(identity.Claims);
            foreach (RoleType r in roles)
            {
                claims.Add(new Claim("role", r.ToString()));
            }
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, tokenUid));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat,
                    ServiceHelper.ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));

            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var authToken = new AuthToken();
            authToken.TokenValue = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(encodedJwt));
            authToken.ExpirationInSeconds = (int)_jwtOptions.ValidFor.TotalSeconds;

            return authToken;

以上代码为我提供了将用户凭据作为输入的令牌。

当我尝试使用邮递员访问以下代码时,它正在向我发送Bearer错误=&#34; invalid_token&#34;和401未经授权。

 [HttpPost("addStudent")]
        [Authorize(Roles = "Director,Student")] 
        public IActionResult Post([FromBody]Student studentFields)
        {            
            if (s == null)
            {
                var student = _studentService.CreateStudent(studentFields);
                return createResponse(201, new
                {
                    studentInfo = student
                });
            }                          
            _logger.LogInformation("Student already added:{0}", s);
            return createErrorResponse("student already added", 404);            
        } 

在标题中,我给出了Authorization = Bearer + token(从api生成的令牌)。我不明白为什么它会给我无效的不记名令牌和401.我见过很多例子,当标题中有令牌时,客户端应该能够访问相应的API。

0 个答案:

没有答案
相关问题