简体   繁体   中英

How to do JWT token based authentication for Asp.Net Core 2.2 MVC Web Application?

I have Asp.Net Core 2.2 MVC web application in which database calls are handled through Asp.Net Core Web Api 2.2 and this Web API will generates the JWT token post verified the Login credentials and returns back to the MVC application with the JWT token.

In Asp.Net core MVC application Controllers decorated with Authorize attribute to validate subsequent request comes from the browser but here i'm not able to validate the JWT token.

So please suggest how to validate the JWT token in Asp.Net Core 2.2 MVC Web Application.

Thanks in advance!

Code:

 services.AddAuthentication(j =>
{
    j.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    j.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    j.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.SaveToken = true;
    x.RequireHttpsMetadata = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        //ValidateLifetime = true,
        //ValidateIssuerSigningKey = true,
        ValidIssuer = "xyz.com",
        ValidAudience = "xyz.com",
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ClockSkew = TimeSpan.FromMinutes(5)
    };
});


app.UseAuthentication();
app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "default",
    template: "{controller=Login}/{action=Login}/{id?}");
});

That seems you are sending request to web api with user's credential, web api validate credential and return to mvc client with JWT token.

In your client app, after getting token and decode to get the claims, you can create new ClaimsIdentity, add your claims and sign-in user. See code sample here .

If you want to know how to decode the JWT token, you can refer to below code samples:

How to decode JWT Token?

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

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