Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How to use authentication service in dependency Injection

I know in depth how to create claims, credentials and JWT and how to create it with hashing algorithm but I don't understand anything about how to configure it in startup class and could not find any documentation.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => options.TokenValidationParameters=new TokenValidationParameters{
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                     .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                ValidateIssuer = false,
                ValidateAudience = false
        });
question from:https://stackoverflow.com/questions/65623219/how-to-use-authentication-service-in-dependency-injection

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

1 Answer

0 votes
by (71.8m points)

JwtBearerDefaults.AuthenticationScheme is a default scheme.

In TokenValidationParameters.

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => 
            options.TokenValidationParameters=new TokenValidationParameters{

            //this is a sign key
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                 .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
            ValidateIssuer = false, //if set true, need to provide API for issuing, such as: http://localhost:5000
            ValidateAudience = false, //if set true, need to provide the audience to be issued, such as: ValidAudience = "api"
            // If all changed to ture,they need to be the same as declared in the token

            //The following is optional
            //Is Expires required to be included in Token Claims
             RequireExpirationTime = true,
            // Allowed server time offset
             ClockSkew = TimeSpan.FromSeconds(300),
            // Whether to verify the validity period of the token, use the current time to compare with NotBefore and Expires in the Token Claims
             ValidateLifetime = true
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...