Hi everyone,
I'm porting my project from ASP.NET 4 WEB API 2 to ASP.NET Core.
The problem I'm facing now is the Authorization. I don't know how to port my ApiAuthorizeAttribute to ASP.NET Core.
Here is my code:
public override void OnAuthorization(HttpActionContext httpActionContext) { // TODO: Implement Git OAuth | Google OAuth here later. // Retrieve email and password. var accountEmail = httpActionContext.Request.Headers.Where( x => !string.IsNullOrEmpty(x.Key) && x.Key.Equals("Email")) .Select(x => x.Value.FirstOrDefault()) .FirstOrDefault(); // Retrieve account password. var accountPassword = httpActionContext.Request.Headers.Where( x => !string.IsNullOrEmpty(x.Key) && x.Key.Equals("Password")) .Select(x => x.Value.FirstOrDefault()).FirstOrDefault(); // Account view model construction. var filterAccountViewModel = new FilterAccountViewModel(); filterAccountViewModel.Email = accountEmail; filterAccountViewModel.Password = accountPassword; filterAccountViewModel.EmailComparision = TextComparision.Equal; filterAccountViewModel.PasswordComparision = TextComparision.Equal; // Find the account. var account = RepositoryAccount.FindAccount(filterAccountViewModel); // Account is not found. if (account == null) { // Treat the account as unthorized. httpActionContext.Response = httpActionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "ACCOUNT_NOT_FOUND"); return; } // Role is not defined which means the request is allowed. if (_roles == null) return; // Role is not allowed if (!_roles.Any(x => x == account.Role)) { // Treat the account as unthorized. httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "ACCOUNT_ACCESS_RESTRICTED"); return; } // Store the requester information in action argument. httpActionContext.ActionArguments["Account"] = account; }
Let me explain my code:
- ApiAuthorizeAttribute inherits AuthorizationFilterAttribute, it overridesOnAuthorization method to do a custom identity validation.
- It reads the requests come from clients, check the email&password parameter in header, query in database and do authorization. In future, I'll implement Google OAuth 2 validation here.
- As the request is not valid, it will throw 401 or 403 with a message to client.
My problem is: In asp.net core, I don't know how to port my code. I've read some posts aboutPolicies and AuthorizationHandler, but found out that I cannot access toHttpRequest& HttpResponse.
Can anyone show me the way please ?
Thank you,