In our asp.net mvc/web api project, we want to customize the authorization using AuthorizeAttribute
. We have noticed that there are two different AuthorizeAtt
This AuthorizeAttribute
implementation worked for me. It's designed for Http Basic Auth but obviously I want to get the User.Identity.IsAuthenticated
and User.Identity.Name
from inside a ApiController
too and this works:
public class ApiAuthAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var session = (ISession)actionContext.Request.GetDependencyScope().GetService(typeof(ISession));
if (actionContext.Request.Headers.Authorization != null)
{
var authConcat = Encoding.UTF8.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.Parameter));
var email = authConcat.Split(':')[0];
var password = authConcat.Split(':')[1];
var user = session.Query().SingleOrDefault(u => u.Email == email);
if (user != null && user.IsAuthenticated(password))
{
actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(user.Email), new string[] { });
return; // and continue with controller
}
}
actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}