Aaron Powell
Aaron Powell

Reputation: 25099

OWIN static files security

I'm building a SPA that will be sitting in a WebAPI/OWIN app (that will be hosted in IIS) that currently has no MVC components what so ever and the / route will just be index.html.

The whole site will need you to log into Azure AD before you can do anything and we'll then pass a bearer token to the WebAPI calls that are made.

How do you make every request to a static file (or at least, every HTML file) require you to be logged in?

Upvotes: 4

Views: 2087

Answers (3)

Sameh Deabes
Sameh Deabes

Reputation: 2973

I will tell you how I did it, and how it works for me.

I am using windows authentication, and here is how I configured it:

OwinHttpListener listener = appBuilder.Properties[typeof(OwinHttpListener).FullName] as OwinHttpListener;
listener.Listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

Then, according to this stackoverflow answer, put the following code between your auth middleware (or the auth code like the above code) and the components you want to protect. It will check to ensure that each request is authenticated.

    app.Use(async (context, next) =>
    {
        var user = context.Authentication.User;
        if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
        {
            context.Authentication.Challenge();
            return;
        }
        await next();
    });

Upvotes: 4

Ciaran O'Neill
Ciaran O'Neill

Reputation: 2634

I haven't attempted that using OWIN middleware yet, but you could always fall back to using a HTTP module that checks for the presence of your auth cookie or bearer token?

Upvotes: 0

Caleb Vear
Caleb Vear

Reputation: 2647

I haven't tested this, but it is what I'd try first so I'm hoping it puts you on the right track.

  • Configure your app so OWIN is serving all static files via the StaticFilesMiddleware. This article talks about how to do that

  • Before you register the static file middleware (with the .UseStaticFiles extension method) create and register your own RequireAuthenticationMiddleware that checks if the request is authenticated and if it isn't returns the appropriate response (401, 403 or whatever). You'll want to register this RequireAuthenticationMiddleware after you configure the OWIN Auth middleware so that the auth details are in the OWIN context.

Upvotes: 1

Related Questions