ASP.NET Core Web API跳过身份验证

7
我正在编写一个ASP.NET Core Web应用程序,使用自定义的基本身份验证,基于以下示例: ASP.NET Core Web API Authentication 现在我的用户控制器中有一个动作,以注册用户。所以我想在这个方法中传递我的自定义属性“SkipAuthAttribute”,以便告诉它,如果有人调用此方法(动作),则必须跳过身份验证(要注册的用户没有登录)。
但是HttpContext类型没有ActionDescriptor来获取操作的自定义属性。
有人知道如何通过一些特定操作跳过身份验证吗?
1个回答

11
更新的答案:您应该尝试根据框架编写代码。例如,中间件不适用于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<BasicAuthenticationMiddleware>();。使用此代码,您可以使用标准属性 Autorize 限制任何控制器:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller

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

原始答案: 来自文档

Add [AllowAnonymous] to the home controller so anonymous users can get information about the site before they register.

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。在我的情况下,基本身份验证是自定义中间件(请参见示例https://dev59.com/fFkT5IYBdhLWcg3wK8dT)。因此,它不关心AllowAnonymous属性。我想读取被调用的控制器的属性。 - Jimy Weiss
ASP.Net Core对于MVC和Web API是相同的。 - Ivan R.
我无法编译这个程序。类BasicAuthenticationOptions无法编译。AuthenticationScheme和AutomaticAuthenticate不可用? - user117499
'BasicAuthenticationOptions' 无法用作泛型类型或方法 'AuthenticationHandler<TOptions>' 中的类型参数 'TOptions'。从 'BasicAuthenticationOptions' 到 'Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions' 没有隐式引用转换。 - user117499
我认为对我来说问题出在Core 2.0上,有人有什么想法吗? - user117499

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接