【发布时间】:2020-07-29 13:23:49
【问题描述】:
我正在为小型原生移动应用程序开发移动 REST API。 我的麻烦是 JWT 在组装 Microsoft.AspNetCore.Authentication.JwtBearer, Version=3.0.2.0
我在 startup.cs 方法 ConfigureServices 中的设置:
services.AddAuthentication()
.AddJwtBearer(CommonHelper.MobileApiConstant.AuthSchemaName, options =>
{
options.SaveToken = true;
options.IncludeErrorDetails = true;
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey =
new SymmetricSecurityKey(
CommonHelper.MobileApiConstant.GetSymmetricSecurityKeyByteArray(_customerCodeConfiguration.CustomerCode)),
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
};
});
我的 API 控制器是:
[Route(CommonHelper.MobileApiConstant.RouteName + "/[controller]/[action]")]
[ApiController]
[Authorize(AuthenticationSchemes = CommonHelper.MobileApiConstant.AuthSchemaName)]
[ApiVersion("1")]
public class AuthenticationController : Controller
{
[HttpGet]
[AllowAnonymous]
[ProducesResponseType(typeof(ResultModel<IMobileCrmUser>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Authenticate([NotNull] string userName, [NotNull] string password)
{
if (!IsOk) // some usless logic
{
return Unauthorized();
}
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
byte[] key = CommonHelper.MobileApiConstant.GetSymmetricSecurityKeyByteArray("My private string");
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddDays(14),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(tokenHandler.WriteToken(token));
}
[HttpGet]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public IActionResult TestMethodGet(string test)
{
if (test == nameof(test))
return Ok("succes");
else
return BadRequest("bad");
}
}
当我调用 Authenticate (Allow anonymous) 方法时,一切正常:
curl -X GET "https://localhost:5001/MobileApi/Authentication/Authenticate?userName=mail%40mail.cz&password=password" -H "accept: text/plain" -H "x-api-version: 1"
返回令牌。然后我想调用TestMethodGet方法请求是:
curl -X GET "https://localhost:5001/MobileApi/Authentication/TestMethodGet?test=test" -H "accept: text/plain" -H "x-api-version: 1" -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImR2ZXNlbHlAY2VudHJ1bS5jeiIsIm5hbWVpZCI6IjIiLCJyb2xlIjpbIkFkbWluIiwiQnVzaW5lc3MiXSwibmJmIjoxNTg3MDMxOTAwLCJleHAiOjE1ODgyNDE1MDAsImlhdCI6MTU4NzAzMTkwMH0.rb_0nxWqedmruaBiaivd8ZrQBBi9SNcgsEQlqrOxhAo"
回复是:
content-length: 0
date: Thu, 16 Apr 2020 10:13:51 GMT
server: Kestrel
status: 401
www-authenticate: Bearer
我不知道错误在哪里以及为什么服务器不给我写更多信息。 API 调用是通过 Swagger 进行的。
我尝试设置 options.IncludeErrorDetails = true;但结果相同。
感谢您的帮助
【问题讨论】:
-
将标题改为
Authorization: Bearer eyJhbGciOi... -
卷曲-X GET “localhost:5001/MMobileApi/Authentication/…” -H “接受:文本/无格式” -H “X-API的版本:1” -H “授权承载:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImR2ZXNlbHlAY2VudHJ1bS5jeiIsIm5hbWVpZCI6IjIiLCJyb2xlIjpbIkFkbWluIiwiQnVzaW5lc3MiXSwibmJmIjoxNTg3MDI5NDkwLCJleHAiOjE1ODc2MzQyOTAsImlhdCI6MTU4NzAyOTQ5MH0.WJNv3k2vUZNOg6Wvjhg56et2KyX9aJ2Np4l83okK0lU” 这给我这个错误:TypeError:无法在“窗口”上执行“获取”:无效名称
-
不知道这个错误是什么意思,但你的标题中有一个错误:'Bearer'这个词应该在':'之后,而不是之前!
-
好的...它有帮助...有什么办法可以避免那里有一个“承载者”吗?
标签: c# jwt swagger asp.net-core-webapi jwt-auth