Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working with a self-hosted OWIN application and am trying to figure out how to require authentication/authorization for all requests (or arbitrary requests).

Some of the individual components in the pipeline have their own Authorization facilities (ex. WebAPI, SignalR, Nancy) but that seems somewhat redundant when I want to restrict everything. Additionally, some middle-ware does not have authorization support (ex. Microsoft.Owin.StaticFiles).

If my OWIN Startup looks something like this:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.RequireSsl();

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        //...
        app.UseGoogleAuthentication();

        // ** Need to add something that restricts access **

        app.UseDirectoryBrowser();
    }
}   

How do I require the user have authenticated (redirecting if necessary) before serving the directory browser? (The directory browser could arbitrarily be other OWIN components.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

Put this between your auth middleware 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();
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...