Reputation: 11
I have an ASP.NET Core Web API secured by JWT and authorization enabled. The API is being consumed with a Blazor client app. I am using services based on REFIT to call the API from the client. The Authorization is based on role and working well. However, I'd like to add an intermediate service which let me filter the API requests / routes based on logged-in user roles BEFORE calling the API.
In other words, I want to add a second security layer and prevent requesting the API when the routes are not allowed for such a role and short circuit the request before reaching the API. My inspiration was from the Laravel Framework Middleware concept used in routes/web.php where each route is declared and named in this file and the middleware, based on user role, is preventing the unauthorized user from reaching the API. I know that in .NET Core the authorization is already well managed by the API but because there will be a lot of requests to it, I'd like to prevent calling the API unnecessarily if the route is not allowed for a specific role.
I tried to add an ActionFilter
, but the API is called first, then the filter, which is not the behavior I want. I tried within a middleware but got same result.
Is there any way to implement a global service (as an entry point for the API or in the Blazor client app) that checks the logged user role and return an unauthorized status code before even reaching the API? A kind of route-role based filter?
Upvotes: 1
Views: 59
Reputation: 8335
You could try implement a custom middleware to decode the accesstoken before authentication in webapi.
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
string accessToken = httpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(' ')[1];
if (accessToken != null)
{
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(accessToken) as JwtSecurityToken;
var roleClaim = jsonToken.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);
if ((roleClaim!= null)&&(roleClaim.Value== "Admin"))
{
await _next(httpContext);
}
else
{
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
await httpContext.Response.WriteAsync("Role invalid");
}
}
else
{
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
await httpContext.Response.WriteAsync("Authorization header missing");
}
await _next(httpContext);
}
}
Then in program.cs use it before routing.
app.UseMiddleware<CustomMiddleware>();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Upvotes: 0