Mtls令牌请求失败并出现错误-AuthenticationScheme:禁止使用x509

时间:2019-06-11 11:35:49

标签: identityserver4

我正在尝试使用Identityserver4的新Mutual TLS客户端身份验证。我已关注Identityserver4网站(Mutual TLS)中的文档。

当我尝试获取MTLS客户端的访问令牌时,出现错误“禁止”。当我检查IdentityServer4日志文件时:

2019-06-11 10:19:26.690 +00:00 [INF] Request finished in 23.3151ms 200 application/json; charset=UTF-8
2019-06-11 10:19:26.784 +00:00 [INF] Request starting HTTP/1.1 GET http://open-banking-authorisation-server-host/.well-known/openid-configuration/jwks  
2019-06-11 10:19:26.786 +00:00 [INF] Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryKeyEndpoint for /.well-known/openid-configuration/jwks
2019-06-11 10:19:26.816 +00:00 [INF] Request finished in 32.05ms 200 application/jwk-set+json; charset=UTF-8
2019-06-11 10:20:41.797 +00:00 [INF] Request starting HTTP/1.1 POST http://open-banking-authorisation-server-host/connect/mtls/token application/x-www-form-urlencoded 80
2019-06-11 10:20:41.814 +00:00 [INF] AuthenticationScheme: x509 was forbidden.

有人可以帮忙吗?

var clientId = "adsjasdjakafklfalvf";
FileStream f = new FileStream("client_cert.crt", FileMode.Open, FileAccess.Read);
int size = (int)f.Length;
byte[] data = new byte[size];
size = f.Read(data, 0, size);
f.Close();

var cert = new X509Certificate2(data);

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);

var newClient = new HttpClient(handler);

var tokenResponse = await newClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
    Address = $"{_authorityBaseUri}/connect/mtls/token",

    ClientId = clientId,
    Scope = "accounts"
});

var accessToken = tokenResponse.AccessToken;

newClient.Dispose();

1 个答案:

答案 0 :(得分:1)

您应该

  1. 在IS4中启用SSL。
  2. 创建客户端证书。
  3. 启用IIS Express接受客户端证书。

    客户端应用

static async Task<TokenResponse> RequestTokenAsync2()
{
    var handler = new SocketsHttpHandler();
    var cert = new X509Certificate2("mtls.test-client.p12", "changeit");
    handler.SslOptions.ClientCertificates = new X509CertificateCollection { cert };

    var client = new HttpClient(handler);

    var disco = await client.GetDiscoveryDocumentAsync("https://localhost:44302");
    if (disco.IsError) throw new Exception(disco.Error);

    var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
        {
            Address = disco                              
                .TryGetValue(OidcConstants.Discovery.MtlsEndpointAliases)
                .Value<string>(OidcConstants.Discovery.TokenEndpoint)
                .ToString(),

                ClientId = "mtls",
                Scope = "api1"
        });

    if (response.IsError) throw new Exception(response.Error);
    return response;
}

IS4

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication()
            .AddCertificate(options =>
            {
                options.AllowedCertificateTypes = CertificateTypes.All;
                options.RevocationMode = X509RevocationMode.NoCheck;
            })

    var builder = services.AddIdentityServer(options =>
        {
            options.MutualTls.Enabled = true;
            options.MutualTls.ClientCertificateAuthenticationScheme = "Certificate";
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseSuccessEvents = true;
        })
        .AddInMemoryIdentityResources(Config.Ids)
        .AddInMemoryApiResources(Config.Apis)
        .AddInMemoryClients(Config.Clients)
        .AddTestUsers(TestUsers.Users);
    builder.AddMutualTlsSecretValidators();
    builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    //app.useh
    app.UseStaticFiles();
    app.UseRouting();

    app.UseIdentityServer();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

进一步阅读:

http://docs.identityserver.io/en/latest/topics/mtls.html#

https://leastprivilege.com/2020/02/07/mutual-tls-and-proof-of-possession-access-tokens-part-1-setup/

https://improveandrepeat.com/2017/07/how-to-configure-iis-express-to-accept-ssl-client-certificates/

https://www.scottbrady91.com/ASPNET/Using-mkcert-for-ASPNET-Core-Development