简体   繁体   中英

JWT Token Authentication - fetch public key from API and use it in TokenValidationParameters in Program.cs of client app

I'm trying to implement a Single Sign On API that uses JWT Token Authentication with asymmetric encryption. I've tested the authentication with success on some endpoint of my API.

Now I want to use this authentication into another web app project (client), the problem is I don't know how to import or fetch the public key from my SSO API in configuration in Program.cs .

SSO API Program.cs

builder.Services.AddSingleton<RsaSecurityKey>(provider => {

    RSA rsa = RSA.Create();
    rsa.ImportRSAPublicKey(
        source: Convert.FromBase64String(builder.Configuration.GetValue<string>("JwtConfig:Asymmetric:PublicKey")),
        bytesRead: out int _
    );

    return new RsaSecurityKey(rsa);
});
builder.Services.AddAuthentication().AddJwtBearer("Asymmetric", options =>
{
    SecurityKey rsa = builder.Services.BuildServiceProvider().GetRequiredService<RsaSecurityKey>();

    options.IncludeErrorDetails = true; // great for debugging

    // Configure the actual Bearer validation
    options.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = rsa,
        ValidAudience = "jwt-test",
        ValidIssuer = "jwt-test",
        RequireSignedTokens = true,
        RequireExpirationTime = true, // <- JWTs are required to have "exp" property set
        ValidateLifetime = true, // <- the "exp" will be validated
        ValidateAudience = true,
        ValidateIssuer = true,
    };

    options.MapInboundClaims = false;
});

Endpoit to return public key

[HttpPost]
[Route("JWK")]
public async Task<string> GetPublicKey()
{
    return _configuration["JwtConfig:Asymmetric:PublicKey"];
}  

Client Webapp Program.cs

builder.Services.AddAuthentication().AddJwtBearer("Asymmetric", options =>
{
    options.IncludeErrorDetails = true; // great for debugging

    // Configure the actual Bearer validation
    options.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = --> some way of fetching the publick key from API (https:.../api/JWK),
        ValidAudience = "jwt-test",
        ValidIssuer = "jwt-test",
        RequireSignedTokens = true,
        RequireExpirationTime = true, // <- JWTs are required to have "exp" property set
        ValidateLifetime = true, // <- the "exp" will be validated
        ValidateAudience = true,
        ValidateIssuer = true,
    };

    // pt a nu-mi mai schimba claims cu acele link-uri xml
    options.MapInboundClaims = false;
});

How can I fetch the public key in this stage of building? Is this the correct way of configuration for using jwt authentication provided by third party app?

I don't think use httpclient to get key from other projects is a good method, Because you can't mare sure if it is safety. If you wanna share key between projects, A common method is to put this key in to a public, safe place. Here i recommend you to use Azure key vault or Azure Blobs , you can refer to this link . If your Api project and another web app project use the same database, You can also save the key into database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM