Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take controller attribute into account from an OWIN authentication middleware

I am currently in the process of putting together a custom OWIN authentication middleware in order to re-use our central authentication mechanism.

In order to control access to the pages, I am using the [Authorize] and [AllowAnonymous] attributes on the controllers.

Even though I understand the the OWIN middleware and the attribute are at very different stages of the page life cycle, I was wondering if there was a way to notify the middleware that the AllowAnonymous attribute is present and there is no need to process the request further.

Typically, having the middleware trigger the authentication process (in my case, implying to go to a remote page - OAuth2 type of authentication) would be an issue when accessing the entry page of a site that is supposed to be accessible anonymously.

Do anyone know a way to accomplish that?

like image 452
E. Jaep Avatar asked Oct 20 '22 10:10

E. Jaep


1 Answers

I know that this is really old, but I had the same issue. In case you haven't already found the answer, but also to help others who come looking:

The thing to remember about middleware is that you get to handle the request before the controller gets it and the response after. So, you don't need to access the attributes directly, you just need to look for their results.

Consider the following:

namespace CustomAuthApp.MVC
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.Use(async (ctx, next) => 
            {
                if (ctx.ExtensionMethodToCheckIfAccessTokenExistsInRequestMaybeAsACookie()) 
                {
                    var ident = new ClaimsIdentity("External");
                    ctx.Request.User = new ClaimsPrincipal(ident);
                }

                await next();

                if (ctx.Response.StatusCode == 401)
                {
                    var loginUri = String.Format("{0}?ReturnUrl={1}", "/Account/Login", ctx.Request.Path);
                    ctx.Response.Redirect(loginUri);
                }
            }
        });
    }
}

We get to check if an Access Token from the oauth service exists and if so, set the ClaimsPrincipal on the request (which will make it bypass the [Authorized] attribute). Then after the request is handled by await next() we can check the response status and set whatever redirects are required.

Obviously, this is an extremely simple case and doesn't take things like Roles or Claims into account, but it should get you down the road.

like image 70
Isaac Hildebrandt Avatar answered Nov 02 '22 23:11

Isaac Hildebrandt