简体   繁体   中英

ASP.Net Authorization Programmatically

I have multiple IHttpHandler in project. I have register those handler to RouteCollection to get trigger on specific URL.

I wanted some handler to be authorized using programmatically. I do not want to use below setting in my web.config . I can't use [Authorize] attribute because it's not using Controller as we see in asp.net MVC.

<system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
</system.web>

Current project doesn't use System.Web.Mvc anywhere.

It's using System.Web.Routing.Route() to register route info using custom created class GenericRouteHandler:IRouteHandler that return IHttpHandler . That Handler example: https://learn.microsoft.com/en-us/do.net/api/system.web.ihttphandler.processrequest?view.netframework-4.8#examples

I'm not sure this would help in old MVC but this is the way you can do it in AspNetCore middleware.

Basically you return 401 handshake on request that is not authorized and the MVC pipeline should authenticate for you. The next time you check if user is auth'ed and skip the handshake if he is or request auth if previous failed.

I do this in a middleware that intercepts the request before it gets to a controller.

if (context.User?.Identity?.IsAuthenticated != true)
{
    context.Response.StatusCode = 401;
    context.Response.Headers.Add("www-authenticate", new StringValues(new[] { "Negotiate", "NTLM" }));
    await context.Response.CompleteAsync();
}

Old MVC should be similar I think but your mileage may vary.

Using the ASP.NET pipeline it's possible to hook into Authenticate events in global.asax , per the question OpenID documentation shows how to authenticate in the Authenticate_Request event, pasted here for clarity:

//file: Global.asax.cs
...
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    OpenIdAuthentication.Authenticate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM