I would like to use jwt tokens for authorization in my ASP.NET MVC website. I have already created an api that generates the jwt token from this tutorial : https://www.c-sharpcorner.com/article/asp-net-web-api-2-creating-and-validating-jwt-json-web-token/
What I have tried:
Now I have added the following nuget packages in my asp.net mvc website :
System.IdentityModel.Tokens.Jwt 5.5.0
Microsoft.Owin.Security.Jwt 4.0.1
Microsoft.AspNet.WebApi.Owin 5.2.3
Microsoft.Owin.Host.SystemWeb 4.0.1
And I have also created a startup file and inserted the following code:
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "example.com",
ValidAudience = "example.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key_12345"))
}
});
I am then using postman to create a jwt token and challenge the website for authorization. The generate token method is the following. (literally like the tutorial):
public Object GetToken()
{
string key = "my_secret_key_12345";
var issuer = "example.com";
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
permClaims.Add(new Claim("valid", "1"));
permClaims.Add(new Claim("userid", "1"));
permClaims.Add(new Claim("name", "bilal"));
var token = new JwtSecurityToken(issuer,
issuer,
permClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials);
var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
return new { data = jwt_token };
}
I have created the following method to challenge the authorization:
[Authorize]
public string checkbystring()
{
return "worked";
}
But when I test it in postman, the following error keeps popping up: IIS 10.0 Detailed Error - 401.0 - Unauthorized
Any suggestions to make this work would be highly appreciated.