使用asp.net Core 3.0传递有效令牌时,邮递员以401返回

时间:2019-12-07 10:55:53

标签: c# asp.net asp.net-mvc .net-core

我在启动时有以下代码:

     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                 .AddJwtBearer(options => {
                     options.TokenValidationParameters = new TokenValidationParameters
                     {
                         ValidateIssuerSigningKey = true,
                         IssuerSigningKey = new SymmetricSecurityKey(key),
                         ValidateIssuer = false,
                         ValidateAudience = false,
                     };
                 });

在auth控制器的Authentication类中,我有以下代码:

 var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Secret").Value);
                     var tokenDescriptor = new SecurityTokenDescripto
         {
            Subject = new ClaimsIdentity(new Claim[]
            {
            new Claim (ClaimTypes.NameIdentifier, user.Id.ToString ()),
            new Claim (ClaimTypes.Name, user.Username)
            }),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), 
          SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

这将返回tokenString。 从邮递员传递带有令牌字符串字符串的url时,返回未经授权的401。 网址是:

localhost:5000/api/hotel/?Authentication=Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIxIiwidW5pcXVlX25hbWUiOiJSdXBhayIsIm5iZiI6MTU3NTcxNDU2MCwiZXhwIjoxNTc1ODAwOTYwLCJpYXQiOjE1NzU3MTQ1NjB9.68L1K3cwRDz7CkL2MP6LdESYO0-2rG5wkyURLzvVIrkg_5XcPb1qVoP2pQgEB8DxbTNVCaBwLV_OsIg2GtTJXg

1 个答案:

答案 0 :(得分:2)

您能否仅将邮递员而不是queryString的令牌添加到请求的标头中。 密钥:验证值:承载{your jwt}