In MVC 4 we can override some methods of AuthorizeAttribute
class to implemenrt custom Authorize attribute.
For an example: https://stackoverflow.com/a/21634723/6120338
public class DemoAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (Authorize(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
throw new HttpResponseException(challengeMessage);
}
private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
var someCode = (from h in actionContext.Request.Headers where h.Key == "demo" select h.Value.First()).FirstOrDefault();
return someCode == "myCode";
}
catch (Exception)
{
return false;
}
}
}
and controller will be
[DemoAuthorize]
public class ValuesController : ApiController{
This is in MVC4. But how to do the same in ASP.NET CORE?
There is no OnAuthorization
, HandleUnauthorizedRequest
, Authorize
overriding method in AuthorizeAttribute
class.