ASP NET CORE身份和Checktoken URL

时间:2019-10-11 20:42:22

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

好吧,我正在尝试将ASP NET CORE 2.1与OAuth2结合使用以在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();
            });

当我尝试通过POSTMAN调用我的API时,得到了以下信息:

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://myidp.com.br/.well-known/openid-configuration'.

好吧,我的IdP中没有知名的 URL,因此在此刻我无法添加它。有没有其他方法可以手动配置没有知名度的URL?

另一件事:我们有一个URL https://myidp.com.br/oauth/tokeninfo,用于检查JWT TOKEN是否有效。

1 个答案:

答案 0 :(得分:1)

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

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

Verifying JWT signed with the RS256 algorithm using public key in C#

您还可以在JwtSecurityTokenHandler中编写自定义System.IdentityModel.Tokens.Jwt package,并覆盖ValidateToken事件以实现自定义验证逻辑。

您也不能使用AddJwtBearer中间件,代码示例与above相同,创建密钥并应用于验证。

通常,验证令牌的正常过程是:

  • 解码令牌
  • 验证索赔(发出者,听众,到期时间...)
  • 验证签名
  • 创建用户主体并登录用户

已更新:

您还可以将自己的签名验证添加到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;
        }
    };

});