'asp.net core webapi JWT validation using authorization filter and JWKS
I am writing an webapi using .net core 6. It need to validate user Authorization JWT token using Authorisation filter and JWKS (keys). May I have any example. I have search google and lots of example are using middleware.
I would like to use Authorisation filter + JWKS
Token header contain below
{
"alg": "RS256",
"typ": "JWT",
**"kid": "asdfb6T82zfdfdfJwc2eruee"**
}
Please any sample code, example would be excellent.
Solution 1:[1]
I'm not familiar with jwks and I tried with jwt token and validate the token in filter as below:
public class JwTFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var jwt = context.HttpContext.Request.Headers["Authorization"].ToString();
var validateParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456")),
ValidateIssuer = true,
ValidIssuer = "http://localhost:5000",
ValidateAudience = true,
ValidAudience = "http://localhost:5001",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
var valiresult = ValidateToken(jwt, validateParameters);
if (valiresult == false)
{
context.HttpContext.Response.StatusCode = 401;
context.Result = new JsonResult(new errmessage() { statuecode = "401", err = "Auth Failed" });
}
}
private static bool ValidateToken(string token, TokenValidationParameters validationParameters)
{
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
return true;
}
catch (Exception)
{
return false;
}
}
}
public class errmessage
{
public string statuecode { get; set; }
public string err { get; set; }
}
In startup class:
services.AddControllers(options =>
{
options.Filters.Add<JwTFilter>();
});
Update: Is it what you want?
public override void OnAuthorization(HttpActionContext context)
{
try
{
var access_token = context.Request.Headers.Authorization?.Parameter;
if (String.IsNullOrEmpty(access_token))
{
//401
context.HttpContext.Response.StatusCode = 401;
context.Result = new JsonResult(new errmessage() { statuecode = "401", err = "Auth Failed" });
}
else
{
//access the public key
var httpclient = new HttpClient();
var jwtKey = httpclient.GetStringAsync(somejwksendpoint).Result;
//chache jwks
var Ids4keys = JsonConvert.DeserializeObject<Ids4Keys>(jwtKey);
var jwk = Ids4keys.keys;
var parameters = new TokenValidationParameters
{
ValidIssuer = issUrl,
IssuerSigningKeys = jwk,
ValidateLifetime = true,
ValidAudience = apiName
};
var handler = new JwtSecurityTokenHandler();
//validate
var vali = handler.ValidateToken(access_token, parameters, out var _);
}
}
catch (Exception ex)
{
context.HttpContext.Response.StatusCode = 401;
context.Result = new JsonResult(new errmessage() { statuecode = "401", err = "Auth Failed" });
}
}
.....
public class Ids4Keys
{
public JsonWebKey[] keys { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

