我正在构建一个反应应用程序,使用Auth0作为我的oauth身份验证并使用ASP.NET核心api对其进行备份。
从React,我将用户重定向到Auth0,我已经设置了一个单页应用程序应用程序。
成功登录后,它将使用代码将用户重定向回我的React应用。
然后我想将该代码转换为JWT令牌,以授权访问后端api,这是失败的地方。
登录后,我使用Auth0提供的示例库并调用:
const { getTokenSilently } = useAuth0();
...
var token = await getTokenSilently();
...
axios({
url: `/api/Folder`,
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
})
它确实提供了令牌,但是对于JWT令牌而言,令牌似乎太小,它在标头中看起来像这样:
Authorization: Bearer 7hExNvsOM14TpY0qUnPbVqpizwLLxynw
我的C#asp.net核心api的响应是:
www-authenticate: Bearer error="invalid_token"
我的C#代码如下所示:startup.cs
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = Configuration["Auth0:Authority"];
options.Audience = Configuration["Auth0:Audience"];
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
IdentityModelEventSource.ShowPII = true; //for debug purposes
....
app.UseAuthentication();
app.UseAuthorization();
folderController.cs
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class FolderController : ControllerBase
{
....
}
似乎您的令牌仅具有标头,它缺少有效负载和签名,即秘密,如果您没有令牌,则应创建它,这是我使用的令牌示例,因为它是基于角色并且没有两要素身份验证,但可能会帮助您:
Controller
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(_appSettings.UserId, user.Id.ToString()),
new Claim(identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault())
}),
Expires = DateTime.UtcNow.AddHours(24),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JwtSecret)), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
Startup.cs
var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSetings:JwtSecret"]);
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
opt.RequireHttpsMetadata = false;
opt.SaveToken = false;
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
);