首页 > 解决方案 > 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 是否有效。

标签: asp.net-core.net-core

解决方案


我假设您正在使用Asymmetric Keys. 通常,公钥信息是从发现文档中自动检索的。如果您需要手动指定它,则需要获取关键参数并创建一个 SecurityKey 对象。您可以参考以下链接获取代码示例:

https://github.com/IdentityServer/IdentityServer4/blob/master/samples/Clients/src/MvcManual/Controllers/HomeController.cs#L148

在 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;
        }
    };

});

推荐阅读