The project that I'm working is running on .NET 6. The ASP.NET Core 6 Web API itself is not generating the JWT, but sending user creds to another authentication API and retrieves the bearer token from there.
My goal is: when user requests an authorized action, the API should take bearer token from header and send it to another API for validation and at the same time take userId
from token and validate the user role with the database.
Currently I got to the point where created simple custom attribute and struggle with moving forward. Current state:
Programs.cs
:
...
//app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Created simple custom attribute:
public class MyAuthorize : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext httpContext)
{
var token = httpContext.HttpContext.Request.Headers.Authorization.ToString().Replace("Bearer ", "");
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
var user = jwt.Claims.First(c => c.Type == "NameIdentifier")?.Value;
}
}
And successfully applied custom attribute to a controller method:
[ApiController]
[Route("api/myapi")]
public class MyController: ControllerBase
{
[HttpGet("test-me")]
[MyAuthorize]
public async Task<IActionResult> TestMe()
{
// do something
return Ok();
}
}
In the current state I can't find a way to inject services into MyAttribute
to create custom logic for token and role validation.
My goal is to achieve something like this:
[HttpGet("test-me")]
[MyAuthorize(Roles="Admin")]
public async Task<IActionResult> TestMe()
{
// do something
return Ok();
}
Where MyAttribute
will send http request to another API to validate the token and execute request to DB and validate user role.