'Intergration testAuthorization filter in asp.net webapi
How can I do intergration test for Authorization filter in asp.net webapi.
In code below I have JWT token which validate the user Authorization. Code example would be excellent.
or How to write intergration test for validating jwt token
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; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
