要求身份验证的所有请求到OWIN应用程序应用程序、身份验证、OWIN

2023-09-03 02:54:45 作者:她与星河皆失.

我正与一个自托管OWIN应用程序,我试图找出如何要求认证/授权的所有请求(或任意请求)。

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).

一些在管道中的各个组件都有自己的授权设备(例如的WebAPI,SignalR,南希),但似乎有些多余,当我想限制一切。此外,一些中间件没有授权支持(例如Microsoft.Owin.StaticFiles)。

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).

如果我OWIN启动看起来是这样的:

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();
    }
}   

我如何要求用户通过身份验证(如果需要的话重定向)服务的目录浏览器之前? (目录浏览器可随意其它OWIN组件。)

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.)

推荐答案

将这个您的身份验证的中间件和要保护的组件之间。它会检查,以确保每个请求进行身份验证。

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();
        });
 
精彩推荐
图片推荐