首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IdentityServer4 Version=“4.1.1”MTLS,MTLS身份验证失败,AuthenticationScheme:证书被禁止

IdentityServer4 Version=“4.1.1”MTLS,MTLS身份验证失败,AuthenticationScheme:证书被禁止
EN

Stack Overflow用户
提问于 2021-01-23 23:00:50
回答 1查看 225关注 0票数 0

IdentityServer客户端已注册

代码语言:javascript
复制
new Client
                {
                    ClientId = "mtls",
                    ClientSecrets =
                    {
                        new Secret("157F807EC5A592201C2B502CEB5934DEF645D6F5", "w.test")
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint
                        },
                    },
                    AccessTokenType = AccessTokenType.Jwt,
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowedScopes = { "resource1.scope1", "resource2.scope1" }
                },

并且Samples ConsoleMTLSClient正在使用相同的证书。

我用IdentityServer->Kestrel->证书解决了子域MTL.*注册的问题,所以我继续前进,但我陷入了新的问题

代码语言:javascript
复制
> [15:21:20 Debug] IdentityServer4.Endpoints.DiscoveryKeyEndpoint Start
> key discovery request
> 
> [15:21:20 Information] Serilog.AspNetCore.RequestLoggingMiddleware
> HTTP GET /.well-known/openid-configuration/jwks responded 200 in
> 64.3172 ms
> 
> [15:21:41 Debug] IdentityServer4.Hosting.MutualTlsEndpointMiddleware
> MTLS authentication failed, error: null.
> 
> [15:21:41 Information]
> Microsoft.AspNetCore.Authentication.Certificate.CertificateAuthenticationHandler
> AuthenticationScheme: Certificate was forbidden.
> 
> [15:21:41 Information] Serilog.AspNetCore.RequestLoggingMiddleware
> HTTP POST /connect/token responded 403 in 19.5811 ms
EN

回答 1

Stack Overflow用户

发布于 2021-01-28 03:59:12

我把它弄好了

首先创建适当的证书usig powershell (以管理员身份运行)步骤1:要与IDS4服务器一起使用-需要注册DNS localhost和mtls.localhost

代码语言:javascript
复制
New-SelfSignedCertificate -Subject "CN=localhost" -DnsName "localhost", "mtls.localhost" -CertStoreLocation cert:\CurrentUser\My -Provider "Microsoft Strong Cryptographic Provider" -FriendlyName "AAABBBIds4mtls test"  -NotAfter (Get-Date).AddYears(1)

它是SelfSigned,所以复制并粘贴(使用Windows certmgr.exe)到‘受信任的根证书颁发机构’

第2步:为客户端创建证书

代码语言:javascript
复制
$cert = New-SelfSignedCertificate -Subject "CN=aaabbb" -DnsName "localhost" -CertStoreLocation cert:\CurrentUser\My -Provider "Microsoft Strong Cryptographic Provider" -FriendlyName "aaabbb20210125"  -NotAfter (Get-Date).AddYears(1)
$cred = Get-Credential
Export-PfxCertificate -Cert $cert -Password $cred.Password -FilePath "./aaabbb20210125.pfx"

然后我使用Scoot Braddy示例Scott Brady blog中的客户端代码

检查它如何与Microsoft.AspNetCore.Authentication.Certificate配合使用

接下来,您需要设置托管在Kestrel上的IdentityServer4项目

Program.cs

代码语言:javascript
复制
 BuildWebHost(args).Run();
.......
 public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
              .UseSerilog()
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Loopback, 5001, listenOptions =>
            {
                listenOptions.UseHttps(new HttpsConnectionAdapterOptions
                {
                    ServerCertificate = **get cert from step 1** 
 from file or windows cert store ///X509.GetCertificate("a9dfaac956575d850f718dde03c9e86a6eb15984", StoreLocation.CurrentUser)
,///RequireCertificate is important switch it off -to get error with client mtls validation
                    ClientCertificateMode = ClientCertificateMode.RequireCertificate ,
                    ClientCertificateValidation = CertificateValidator.DisableChannelValidation
                });
            });
            options.Listen(IPAddress.Loopback, 5000);
        })
        .Build();

检查您是否已添加了nuget包Microsoft.AspNetCore.Authentication.Certificate

Startup.cs

代码语言:javascript
复制
            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseSuccessEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.EmitScopesAsSpaceDelimitedStringInJwt = true;
                options.MutualTls.Enabled = true;
                options.MutualTls.DomainName = "mtls";
                options.MutualTls.ClientCertificateAuthenticationScheme = "Certificate";
                //options.MutualTls.AlwaysEmitConfirmationClaim = true;
            })
                .AddInMemoryApiScopes(Configuration.GetApiScopes())
                .AddInMemoryApiResources(Configuration.GetApiResources())
                .AddInMemoryIdentityResources(Configuration.GetIdentityResources())
                .AddInMemoryClients(Configuration.GetClients())
                .AddMutualTlsSecretValidators() 
       .AddSigningCredential(X509.GetCertificate("88D603D7F65B07109E4D0FFBECCCD70881F902F8", StoreLocation.CurrentUser));//add your certificate 
 
 services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)      
 .AddCertificate(options =>
    {
             options.AllowedCertificateTypes = CertificateTypes.All; //selfsigned too
                options.RevocationMode = X509RevocationMode.NoCheck;//for development/testing
        options.Events = new CertificateAuthenticationEvents
        {
            OnCertificateValidated = context =>
            {
                var claims = new[]
                {
                                new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                                new Claim(ClaimTypes.Name, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                };

                context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                context.Success();

                return Task.CompletedTask;
            }
        };
    });

设置mtlsclient mtlsclient

代码语言:javascript
复制
....
        static async Task<TokenResponse> RequestTokenAsync()
        {
            var client = new HttpClient(GetHandler());

            var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");    "https://identityserver.local");
............

static SocketsHttpHandler GetHandler()
        {
            var handler = new SocketsHttpHandler();
            
            var cert = new X509Certificate2("client.p12", "changeit");///**get cert from step 2**
            handler.SslOptions.ClientCertificates = new X509CertificateCollection { cert };

            return handler;
        }

设置主机文件C:\Windows\System32\drivers\etc

代码语言:javascript
复制
# To allow the MTLS for identityServer4
127.0.0.1 mtls.localhost
127.0.0.1 identityserver.local
# End of section

最后运行IDS4,运行mtlsclient

代码语言:javascript
复制
[19:36:48 Debug] IdentityServer4.Endpoints.TokenEndpoint
Start token request.

[19:36:48 Debug] IdentityServer4.Validation.ClientSecretValidator
Start client validation

[19:36:48 Debug] IdentityServer4.Validation.BasicAuthenticationSecretParser
Start parsing Basic Authentication secret

[19:36:48 Debug] IdentityServer4.Validation.PostBodySecretParser
Start parsing for secret in post body

[19:36:48 Debug] IdentityServer4.Validation.PostBodySecretParser
client id without secret found

[19:36:48 Debug] IdentityServer4.Validation.ISecretsListParser
Parser found secret: PostBodySecretParser

[19:36:48 Debug] IdentityServer4.Validation.MutualTlsSecretParser
Start parsing for client id in post body

[19:36:48 Debug] IdentityServer4.Validation.ISecretsListParser
Parser found secret: MutualTlsSecretParser

[19:36:48 Debug] IdentityServer4.Validation.ISecretsListParser
Secret id found: mtls

[19:36:48 Debug] IdentityServer4.Stores.ValidatingClientStore
client configuration validation for client mtls succeeded.

[19:36:48 Debug] IdentityServer4.Validation.HashedSharedSecretValidator
Hashed shared secret validator cannot process X509Certificate

[19:36:48 Debug] IdentityServer4.Validation.ISecretsListValidator
Secret validator success: X509ThumbprintSecretValidator

[19:36:48 Debug] IdentityServer4.Validation.ClientSecretValidator
Client validation success

[19:36:48 Information] IdentityServer4.Events.DefaultEventService
{"ClientId": "mtls", "AuthenticationMethod": "X509Certificate", "Category": "Authentication", "Name": "Client Authentication Success", "EventType": "Success", "Id": 1010, "Message": null, "ActivityId": "0HM62U8QNJK8Q:00000001", "TimeStamp": "2021-01-27T18:36:48.0000000Z", "ProcessId": 27900, "LocalIpAddress": "127.0.0.1:5001", "RemoteIpAddress": "127.0.0.1", "$type": "ClientAuthenticationSuccessEvent"}

[19:36:48 Debug] IdentityServer4.Validation.TokenRequestValidator
Start token request validation

[19:36:48 Debug] IdentityServer4.Validation.TokenRequestValidator
Start client credentials token request validation

[19:36:48 Debug] IdentityServer4.Validation.TokenRequestValidator
mtls credentials token request validation success

[19:36:48 Information] IdentityServer4.Validation.TokenRequestValidator
Token request validation success, {"ClientId": "mtls", "ClientName": null, "GrantType": "client_credentials", "Scopes": "AconsApi ApiTwo", "AuthorizationCode": "********", "RefreshToken": "********", "UserName": null, "AuthenticationContextReferenceClasses": null, "Tenant": null, "IdP": null, "Raw": {"grant_type": "client_credentials", "scope": "AconsApi ApiTwo", "client_id": "mtls"}, "$type": "TokenRequestValidationLog"}

[19:36:48 Debug] IdentityServer4.Services.DefaultClaimsService
Getting claims for access token for client: mtls

[19:36:49 Information] IdentityServer4.Events.DefaultEventService
{"ClientId": "mtls", "ClientName": null, "RedirectUri": null, "Endpoint": "Token", "SubjectId": null, "Scopes": "AconsApi ApiTwo", "GrantType": "client_credentials", "Tokens": [{"TokenType": "access_token", "TokenValue": "****hTTg", "$type": "Token"}], "Category": "Token", "Name": "Token Issued Success", "EventType": "Success", "Id": 2000, "Message": null, "ActivityId": "0HM62U8QNJK8Q:00000001", "TimeStamp": "2021-01-27T18:36:49.0000000Z", "ProcessId": 27900, "LocalIpAddress": "127.0.0.1:5001", "RemoteIpAddress": "127.0.0.1", "$type": "TokenIssuedSuccessEvent"}
[19:36:49 Debug] IdentityServer4.Endpoints.TokenEndpoint
Token request success.

MTLS客户端

代码语言:javascript
复制
Access Token (decoded):
{
  "alg": "RS256",
  "kid": "88D603D7F65B07109E4D0FFBECCCD70881F902F8RS256",
  "typ": "at+jwt",
  "x5t": "iNYD1_ZbBxCeTQ_77MzXCIH5Avg"
}
{
  "nbf": 1611772608,
  "exp": 1611776208,
  "iss": "https://localhost:5001",
  "aud": [
    "Api",
    "ApiTwo"
  ],
  "client_id": "mtls",
  "jti": "447F97582B1C1ADDABB237B7E36C4F32",
  "iat": 1611772608,
  "scope": "AconsApi ApiTwo",
  "cnf": {
    "x5t#S256": "1F9sG7CCC77SL9LI9edhus9Ga8AKJgfE5eraKvrv438"
  }
}

摘要

  • 1.安装...\ets\hosts
  • 2.prepare证书step1 step2 (makecert.exe不适用于SAN(使用者备用名称))
  • 3.安装IDS4 Program.cs step2 not来自step2

的客户端证书

代码语言:javascript
复制
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65860684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档