I have implemented the Azure AD Authentication in ASP.Net Core 6 using the standard way and have used the [Authorize] attribute on top of the controller class. All these are working fine.
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd");
Apart from the Authentication, I am trying to build the custom Authorization using TypeFilterAttribute class. Code snippet below:
public class CustomAuthorizeAttribute : TypeFilterAttribute
{
public CustomAuthorizeAttribute(params Roles[] roles) : base(typeof(CustomAuthorizeFilter))
{
Roles[] _roles = roles;
Arguments = new object[] { _roles };
}
}
public class CustomAuthorizeFilter : IAuthorizationFilter
{
private readonly Roles[] _roles;
private readonly IUserService _userService;
public CustomAuthorizeFilter(Roles[] roles, IUserService userService)
{
_roles = roles ?? throw new UnauthorizedAccessException("OnAuthorization : Missing role parameter");
_userService = userService;
}
public async void OnAuthorization(AuthorizationFilterContext context)
{
if (context != null && context.HttpContext != null &&
context.HttpContext.User != null &&
context.HttpContext.User.Identity != null)
{
string? userEmailId = context.HttpContext.User.Identity.Name;
if (string.IsNullOrEmpty(userEmailId))
{
context.Result = new ContentResult()
{
Content = "OnAuthorization : Invalid User : Email Id is not present",
StatusCode = 401
};
return;
}
var userDetails = await _userService.GetUserProfile(userEmailId);
if (userDetails == null)
{
context.Result = new ContentResult()
{
Content = "OnAuthorization : Invalid User : User does not exist",
StatusCode = 403
};
}
}
}
}
Usage: For each controller action method, I would like to the Roles who can access the Api. In the below code snippet, Roles is an enum. Basically, I am trying to implement the Role based access for each of the Api.
[CustomAuthorize(Roles.Admin1,Roles.Admin2)]
Issue: The CustomAuthorizeAttribute is getting called. But, the controller action is being invoked ir-respective of the Authentication within the CustomAuthorizeAttribute.
what is that I am missing here?
CustomAuthorizeAttribute
in Program.cs file? If you have, pls delete it. – Lonne