我一直在冒险让 JWT 在 DotNet 核心 2.0 上工作(今天达到最终版本)。有大量的文档,但所有示例代码似乎都在使用已弃用的 API,并且对 Core 来说是新鲜的,弄清楚它应该如何实现确实令人眼花缭乱。我尝试使用 Jose,但应用程序。UseJwtBearerAuthentication 已被弃用,并且没有关于下一步做什么的文档。
有没有人有一个使用 dotnet core 2.0 的开源项目,它可以简单地从授权标头解析 JWT 并允许我授权对 HS256 编码的 JWT 令牌的请求?
下面的类没有抛出任何异常,但没有请求被授权,我也没有得到任何迹象表明它们为什么是未经授权的。响应是空的 401,所以对我来说这表明没有例外,但秘密不匹配。
一件奇怪的事情是,我的令牌是使用 HS256 算法加密的,但我没有看到任何指标告诉它强制它在任何地方使用该算法。
这是我到目前为止的课程:
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Site.Authorization
{
public static class SiteAuthorizationExtensions
{
public static IServiceCollection AddSiteAuthorization(this IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET_KEY"));
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<SecurityKey>{ signingKey },
// Validate the token expiry
ValidateLifetime = true,
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.IncludeErrorDetails = true;
o.TokenValidationParameters = tokenValidationParameters;
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 401;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
});
return services;
}
}
}