【问题标题】:ASP.NET Core Web API Skip AuthenticationASP.NET Core Web API 跳过身份验证
【发布时间】:2017-11-24 10:15:51
【问题描述】:

我正在编写一个使用自定义基本身份验证的 ASP.NET Core Web 应用程序,基于以下示例: ASP.NET Core Web API Authentication 现在我在我的用户控制器中有一个动作来注册用户。所以我想将此方法传递给我的自定义属性“SkipAuthAttribute”,以便说,如果有人调用此方法(操作),您必须跳过身份验证(要注册的用户没有登录)。

但是HttpContext类型没有ActionDescriptor来获取动作的自定义属性

认识某人,如何通过某些特定操作跳过身份验证?

【问题讨论】:

    标签: c# .net asp.net-web-api asp.net-core


    【解决方案1】:

    更新答案: 您应该尝试根据框架编写代码。示例中的中间件不适合 ASP.NET Core MVC。这是我的例子:

    public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
        {
            protected override Task<AuthenticateResult> HandleAuthenticateAsync()
            {
                var authHeader = (string)this.Request.Headers["Authorization"];
    
                if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
                {
                    //Extract credentials
                    string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                    Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                    string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
    
                    int seperatorIndex = usernamePassword.IndexOf(':');
    
                    var username = usernamePassword.Substring(0, seperatorIndex);
                    var password = usernamePassword.Substring(seperatorIndex + 1);
    
                    if (username == "test" && password == "test")
                    {
                        var user = new GenericPrincipal(new GenericIdentity("User"), null);
                        var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
                        return Task.FromResult(AuthenticateResult.Success(ticket));
                    }
                }
    
                return Task.FromResult(AuthenticateResult.Fail("No valid user."));
            }
        }
    
        public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
        {
            public BasicAuthenticationMiddleware(
               RequestDelegate next,
               IOptions<BasicAuthenticationOptions> options,
               ILoggerFactory loggerFactory,
               UrlEncoder encoder)
               : base(next, options, loggerFactory, encoder)
            {
            }
    
            protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
            {
                return new BasicAuthenticationHandler();
            }
        }
    
        public class BasicAuthenticationOptions : AuthenticationOptions
        {
            public BasicAuthenticationOptions()
            {
                AuthenticationScheme = "Basic";
                AutomaticAuthenticate = true;
            }
        }
    

    在 Startup.cs 注册 - app.UseMiddleware&lt;BasicAuthenticationMiddleware&gt;();。使用此代码,您可以限制任何具有标准属性Autorize 的控制器:

    [Authorize(ActiveAuthenticationSchemes = "Basic")]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    

    如果您在应用程序级别应用授权过滤器,请使用属性AllowAnonymous

    原答案: From documentation

    [AllowAnonymous] 添加到家庭控制器,这样匿名用户就可以在注册之前获取有关该站点的信息。

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Authorization;
    
    namespace ContactManager.Controllers {
    [AllowAnonymous]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    

    【讨论】:

    • 没有 HomeController,我没有使用 MVC,但正如所说的 Web API。在我的情况下,基本身份验证是一个自定义中间件(参见示例 stackoverflow.com/questions/38977088/… )。所以它不关心 AllowAnonymous 属性。我想阅读被调用的控制器的属性。
    • ASP.Net Core 对于 MVC 和 Web API 是一样的。
    • 我无法编译。 BasicAuthenticationOptions 类无法编译。 AuthenticationScheme,AutomaticAuthenticate 不可用?
    • BasicAuthenticationOptions' 不能用作泛型类型或方法 'AuthenticationHandler' 中的类型参数 'TOptions'。没有从“BasicAuthenticationOptions”到“Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions”的隐式引用转换。
    • 我认为我的问题是 Core 2.0 > 有人有什么想法吗?
    猜你喜欢
    • 2016-12-22
    • 2022-01-27
    • 2018-01-28
    • 2018-06-29
    • 2020-07-27
    • 2018-03-15
    • 2012-06-16
    • 2017-10-22
    • 1970-01-01
    相关资源
    最近更新 更多