Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

IdentityServer4 Version=“4.1.1” MTLS, MTLS authentication failed,AuthenticationScheme: Certificate was forbidden

IdentityServer Client is registered

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" }
                },

and Samples ConsoleMTLSClient is using the same certificate.

I solved problem with IdentityServer->Kestrel->certificate for sub-domain mtls.* registering , so I go forward but I'm stuck into the new problem

> [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
question from:https://stackoverflow.com/questions/65860684/identityserver4-version-4-1-1-mtls-mtls-authentication-failed-authentications

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got it working

First create proper certificate usig powershell ( run as administrator) Step 1: to use with IDS4 server - need to register DNS localhost and mtls.localhost

New-SelfSignedCertificate -Subject "CN=localhost" -DnsName "localhost", "mtls.localhost" -CertStoreLocation cert:CurrentUserMy -Provider "Microsoft Strong Cryptographic Provider" -FriendlyName "AAABBBIds4mtls test"  -NotAfter (Get-Date).AddYears(1)

it's SelfSigned so copy and paste ( using Windows certmgr.exe) to 'trusted root certification authorities'

Step 2: create certificate for Client

$cert = New-SelfSignedCertificate -Subject "CN=aaabbb" -DnsName "localhost" -CertStoreLocation cert:CurrentUserMy -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"

then I use Client code from Scoot Braddy sample Scott Brady blog

to check how it works with Microsoft.AspNetCore.Authentication.Certificate

next you need setup your IdentityServer4 project hosted on Kestrel

Program.cs

 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();

Check you have added nuget package Microsoft.AspNetCore.Authentication.Certificate

Startup.cs

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

Setup mtlsclient mtlsclient

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

setup your host file C:WindowsSystem32driversetc

# To allow the MTLS for identityServer4
127.0.0.1 mtls.localhost
127.0.0.1 identityserver.local
# End of section

and finally at the end run IDS4 ,run mtlsclient

[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 Client

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"
  }
}

summary

  • 1.setup ...etshosts
  • 2.prepare certificates step1 step2 (makecert.exe does not work with SAN( Subject Alternative Names) )
  • 3.setup IDS4 Program.cs Startup.cs
  • 4.use mtlsclient certificate from step2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...