I am using jwt tokens in my project. When the client logins, he will receive a token with his device id (in mobile) -that was sent to the server in the request body- as the payload...
The thing I want to do is for further requests when the client sends his device id in the body (as a convention in my project) and of course the token in the header request, I want to check if the device id and the token's payload are equal or not.
I did this in a service like this:
public class AuthenticationService
{
public bool IsAuthenticated(HttpRequest req, string deviceId)
{
var token = req.Headers["authorization"];
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken tokenS;
foreach (var stringValue in token)
{
var ss = stringValue.Replace("Bearer ", "");
if (handler.CanReadToken(ss))
{
tokenS = handler.ReadToken(ss) as JwtSecurityToken;
return tokenS.Claims.Any(c => c.Value == deviceId);
}
}
return false;
}
}
And I should inject it in every controller that I want to authorize the user...
if (_authenticationService.IsAuthenticated(Request, deviceId))
{
_logger.LogInformation("authorized!");
}
else
{
_logger.LogCritical("unauthorized");
}
I want to know that if there is a more cleaner way of doing this? Something to do in the Startup class when I'm configuring the Authentication:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(
Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
};
});