Hay, I have angular 7 fronted project and asp.net core web API. after i create JWT web token from web API, i return to fronted and it will save in local storage. after i want to send request to web API i will put JWT web token to request header part. that will work fine. so i want to authenticate request using JWT payload data. My JWT payload data have logging user name, user role some of information. i want to check it's valid token when get product details by http get request. can you help me for authenticate in asp.net core web api.

asp.net core web api , Angular 7 cli

Startup.cs - WEB API

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
 {
  options.TokenValidationParameters = new TokenValidationParameters
  {
  ValidateIssuer = true,
  ValidateAudience = true,
  ValidateLifetime = true,
  ValidateIssuerSigningKey = true,
  ValidIssuer = Configuration["Jwt:Issuer"],
  ValidAudience = Configuration["Jwt:Issuer"],
  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
 };
});

services.AddMvc();

Build Web token - WEB API

private string BuildToken(MYWebApi.Models.CustomerModel user)
{
  var claims = new[] {
  new Claim(JwtRegisteredClaimNames.NameId,user.CusId.ToString()),
  new Claim(JwtRegisteredClaimNames.Sub,user.CusName),
  new Claim(JwtRegisteredClaimNames.Email,user.CusEmail),
  new Claim("role","user"),
};

 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

 var token = new JwtSecurityToken(_config["Jwt:Issuer"],
  _config["Jwt:Issuer"],
 claims,
 expires: DateTime.Now.AddMinutes(30),
 signingCredentials: creds);

 return new JwtSecurityTokenHandler().WriteToken(token);
}

Put token to header part - FRONT END

 @Injectable( )
    export class TokenInterceptorService implements HttpInterceptor{

      constructor(private injector:Injector) { }

      intercept(req, next){
        let serverService = this.injector.get(ServerService)
        let tokenizedReq = req.clone({
            setHeaders:{
              Autherization:`Bearer ${serverService.getToken()}`
            }
         })
        return next.handle(tokenizedReq)
      }
    }

Controller - WEB API

[Route("GetProduct")]
        [HttpGet]
        public List<ProductModel> GetProduct(int productId)
        {
            var repo = new MEData.Repository.ProductRepo();

            var productData = repo.GetProduct(productId);

            return productData;
        }

2 Answers

0
Mohsin Mehmood On

Ensure you have app.UseAuthentication(); code added before app.UseMvc(); in Configure method of Startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseAuthentication();

            app.UseMvc();
        }

And then also add [Authorize]attribute at action or controller level based on your requirements

0
Shahzad Hassan On

Try the following options below, in addition to app.UseAuthentication() call:

1. Apply the [Authorize] attribute with the AuthenticationSchemes

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("GetProduct")]
[HttpGet]
public List<ProductModel> GetProduct(int productId)
{
   //...
}

In addition, try adding the following line in ConfigureServices

services.AddAuthorization();

2. Try using the services.AddAuthorization with policies, and selected scheme

services.AddAuthorization(options =>
{
    options.AddPolicy("Jwt", policy =>
    {
        policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });
});

Then use the policy using [Authorize] attribute

[Authorize(Policy = "Jwt")]
[Route("GetProduct")]
[HttpGet]
public List<ProductModel> GetProduct(int productId)
{
   //...
}

In general, I think services.AddAuthorization line is required. See which of the options works for you.