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;
}
Ensure you have
app.UseAuthentication();
code added beforeapp.UseMvc();
in Configure method of Startup classAnd then also add
[Authorize]
attribute at action or controller level based on your requirements