using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; namespace HRD.LDAPService.JWT { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class JWTAuthorizeAttribute : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { if (JwtTokenConfig.AktivateAuthorizationFilter) { bool isInWhiteList = false; //allow access with logn & pwd and without Authorization token var path = context?.HttpContext.Request.Path.Value; if (!string.IsNullOrEmpty(path)) { if (JwtTokenConfig.IsInBlackList(path)) { context.Result = new JsonResult(new { message = $"Unauthorized access. Path is in a blacklist: '${path}'" }) { StatusCode = StatusCodes.Status403Forbidden }; } isInWhiteList = JwtTokenConfig.IsInWhiteList(path); if (!isInWhiteList) { //need jwt check var check = (string)context.HttpContext.Items[JwtGlobals.HttpContextItem_IsValidHenselToken]; if (check == null) { context.Result = new JsonResult(new { message = $"Unauthorized access. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized }; } } } } } } }