简体   繁体   English

dotnet core 3.0 WebApi、applicationPart和授权

[英]dotnet core 3.0 WebApi, applicationPart and authorization

We have a modular application, which means that our api controllers get loaded during startup.我们有一个模块化应用程序,这意味着我们的 api 控制器会在启动期间加载。 We load the controllers into the applicationPart like this:我们将控制器加载到 applicationPart 中,如下所示:

services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .ConfigureApplicationPartManager(applicationPartManager =>
            {
                foreach (var module in _modules)
                {
                    var apiControllerAssemblies = module.GetApiControllerAssemblies();

                    foreach (var apiControllerAssembly in apiControllerAssemblies)
                        applicationPartManager.ApplicationParts.Add(new AssemblyPart(apiControllerAssembly));
                }
            });

We want to protect our apis with Basic authentication.我们希望通过基本身份验证来保护我们的 api。 I've created a middleware like this:我创建了一个这样的中间件:

 public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, 
                                          ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return AuthenticateResult.Fail("Missing Authorization 
                                                Header");
            //More to come
        }
    }

The middleware is registered in startup.cs like this:中间件在 startup.cs 中注册,如下所示:

services.AddAuthentication("Basic")
             .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("Basic", null);

Accessing localhost: will always trigger the HandleAuthenticateAsync method.访问 localhost: 将始终触发HandleAuthenticateAsync方法。 However when I try to access the localhost:/user/users endpoint the method never hit the breakpoint and will always result in a HTTP 401 Unauthorized.但是,当我尝试访问 localhost:/user/users 端点时,该方法永远不会遇到断点,并且总是会导致 HTTP 401 Unauthorized。 The controller itself is marked with the Authorize attribute. controller 本身标有Authorize属性。

Any ideas where it goes wrong?有什么想法会出错吗? Any hints to where I should start looking for a solution?关于我应该从哪里开始寻找解决方案的任何提示?

Thanks!谢谢!

Not sure if this helps, but when I had to implement Authentication this is what I did.不确定这是否有帮助,但是当我必须实现身份验证时,这就是我所做的。

a.一个。 Declare a class extending AuthenticationSchemeOptions声明一个扩展AuthenticationSchemeOptions的 class

    public class CustomAuthOptions: AuthenticationSchemeOptions
    {
    }

b.湾。 Declare a class implementing the AuthenticationHandler<TOptions>声明一个实现AuthenticationHandler<TOptions>的 class

    internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
    {
        IHttpContextAccessor _httpContextAccessor;
        IUser _user;

        public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, 
            IHttpContextAccessor httpContextAccessor, IUser user) : base(options, logger, encoder, clock)
        {
            _httpContextAccessor = httpContextAccessor;
            _user = user;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            //logic to authenticate
        }

        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            //more code
        }
   }

c. c。 Add an extension method to the AuthenticationBuilder classAuthenticationBuilder class 添加扩展方法

        public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder,
            Action<CustomAuthOptions> config)
        {
            return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("CheckInDB", "CheckInDB", config);
        }

d. d。 Finally in the Startup.cs最后在Startup.cs

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "CheckInDB";
                options.DefaultChallengeScheme = "CheckInDB";
            }).AddCustomAuth(c => { });

This may be more than what is needed, but when I was in the same boat, a couple of months ago, I spent a good few days piecing all of this together.这可能超出了需要,但是当我在同一条船上时,几个月前,我花了好几天时间将所有这些拼凑在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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