asp.net-core - ASP NET CORE 身份和校验令牌 URL
问题描述
好吧,我正在尝试使用带有 OAuth2 的 ASP NET CORE 2.1 在 IdP(身份提供者)中进行身份验证,所以我有以下内容:
services.AddAuthentication()
.AddJwtBearer(options =>
{
// The API resource scope issued in authorization server
options.Audience = "resource.server.api";
// URL of my authorization server
options.Authority = "https://myidp.com.br";
});
// Making JWT authentication scheme the default
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
当我尝试调用我的 API 思想 POSTMAN 时,我得到了以下信息:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://myidp.com.br/.well-known/openid-configuration'.
好吧,我的 IdP 中没有众所周知的URL,我无法在这个项目中添加它。有没有其他方法可以手动配置 URL 而没有 well-known ?
另一件重要的事情:我们有一个 URLhttps://myidp.com.br/oauth/tokeninfo
来检查 JWT TOKEN 是否有效。
解决方案
我假设您正在使用Asymmetric Keys
. 通常,公钥信息是从发现文档中自动检索的。如果您需要手动指定它,则需要获取关键参数并创建一个 SecurityKey 对象。您可以参考以下链接获取代码示例:
在 C# 中使用公钥验证使用 RS256 算法签名的 JWT
也可以在自定义JwtSecurityTokenHandler
中编写System.IdentityModel.Tokens.Jwt package
,并重写ValidateToken
事件来实现自定义的验证逻辑。
您也可以不使用AddJwtBearer
中间件,代码示例与上面相同,创建您的密钥并应用于验证。
通常,验证令牌的规范过程是:
- 解码令牌
- 验证声明(发行者、受众、到期时间......)
- 验证签名
- 创建用户主体并登录用户
更新 :
您还可以将自己的签名验证添加到 TokenValidationParameters :
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
SignatureValidator =
delegate (string token, TokenValidationParameters parameters)
{
var jwt = new JwtSecurityToken(token);
var httpClient = new HttpClient();
var requestData = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("xxxxxx"),
};
//pass toekn to your endpoint and check result
if (false)
{
throw new Exception("Token signature validation failed.");
}
return jwt;
}
};
});
推荐阅读
- pycharm - 龟函数在pycharm中不起作用
- java - Azure Java SDK - 同时使用映像创建多个 VM
- tensorflow - 给定一个 Tensoflow MetaGraph,我怎样才能找到这个图的输入张量和输出张量?
- r - R 数小时内无法处理繁重的任务
- xml - 使用 SoapUI 发出请求时面临的问题
- cassandra - 可以直接将 ScyllaDB 2.1.x 升级到 ScyllaDB 3.xx 吗?
- spring-boot - 如何通过弹性搜索找到排序后的数据——spring boot
- python - 错误:引发 portNotOpenError serial.serialutil.SerialException:尝试使用未打开的端口
- symfony - 所有 URL 都转到 web/index.html
- android - 使用底部工作表对话框时,应用程序 MapFragment 锁定为模式