Reputation: 269
Is it possible to check rate limit after authentication has been done?
I would like to use one of the claims as client id and impose different rate limits depending on this claim.
Upvotes: 3
Views: 1549
Reputation: 892
I haven't tried the solution yet but I figure out it could be possible with following approach.
Create you own CustomRateLimitConfiguration
as pointed in the followind documentation.
https://github.com/stefanprodan/AspNetCoreRateLimit/wiki/Resolve-Contributors
Out of the box the current version of AspNetCoreRateLimit
(4.0.1
) has support for only supports ClientHeaderResolveContributor.cs
as resolver for ClientId rate limiting.
Hence you need to create custom resolver(ClientClaimResolveContributor
) by inheriting from IClientResolveContributor
, use the following code as reference from AspNetCoreRateLimit
github repository.
https://github.com/stefanprodan/AspNetCoreRateLimit/blob/master/src/AspNetCoreRateLimit/Resolvers/ClientHeaderResolveContributor.cs
Read the authentication header using HttpContext
and parse the jwt using following code.
var token = new JwtSecurityTokenHandler().ReadJwtToken(tokenstring);
var claim = token.Claims.First(c => c.Type == "email").Value;
return claim;
The custom resolver class might look like this.
public class ClientAuthClaimResolveContributor : IClientResolveContributor
{
private readonly string _cliamName;
public ClientHeaderResolveContributor(string claimName)
{
_claimName = claimName;
}
public Task<string> ResolveClientAsync(HttpContext httpContext)
{
string jwtToken = null;
Claim claimToRead = null;
if (httpContext.Request.Headers.TryGetValue("Authorization", out var values))
{
jwtToken = values.First();
var token = new JwtSecurityTokenHandler().ReadJwtToken(jwtToken);
claimToRead = token.Claims.First(c => c.Type == claimName).Value;
}
return Task.FromResult(claimToRead);
}
}
Upvotes: 3