Hi @Dotnet Engineer,
According to the github codes you have shared, I found you follow the asp.net web api article to use the AuthorizationFilterAttribute which will not work inside asp.net core.
Inside asp.net core, normally. we will use authentication middleware with the Asp.net Core web api with JWT authentication or else.
If you still want to use CustomAuthenticationAttribute, I suggest you could consider using the IAuthorizationFilter.
Details, you could refer to below codes:
public void OnAuthorization(AuthorizationFilterContext context)
{
//check access and put your own logic to get the username and password
if (IsAuthorizedUser("test", "pass"))
{
//all good, add optional code if you want. Or don't
// Create a new claim
var customClaim = new Claim("CustomClaimType", "CustomClaimValue");
// Add the claim to the user's identity
((ClaimsIdentity)context.HttpContext.User.Identity).AddClaim(customClaim);
}
else
{
//DENIED!
//return "ChallengeResult" to redirect to login page (for example)
context.Result = new UnauthorizedObjectResult("Unauth");
}
}
If you want to read the claim inside the controller, you could refer to below codes:
public async Task<ActionResult<IEnumerable<Visit>>> GetVisits()
{
//if (_context.Visits == null)
//{
// return NotFound();
//}
// return await _context.Visits.ToListAsync();
//get the claim value
var re = Request.HttpContext.User.Claims.Where(x => x.Type == "CustomClaimType").FirstOrDefault().Value;
return new List<Visit>() { new Visit { Visitid=1 } };
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.