Jim*_*iss 2 .net c# asp.net-web-api asp.net-core
我正在使用自定义基本身份验证编写ASP.NET Core Web应用程序,基于以下示例: ASP.NET Core Web API身份验证 现在,我在用户控制器中有一个操作,以便注册用户.所以我想传递这个方法我的自定义属性"SkipAuthAttribute",以便说,如果有人调用这个方法(动作)你必须跳过认证(想要注册的用户,没有登录).
但是HttpContext类型没有ActionDescriptor来获取操作的自定义属性
知道某人,我怎么能通过某些具体行动跳过认证呢?
更新的答案: 您应该尝试根据框架编写代码.示例中的中间件不适用于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;
}
}
Run Code Online (Sandbox Code Playgroud)
在Startup.cs注册 - app.UseMiddleware<BasicAuthenticationMiddleware>();.使用此代码,您可以使用standart属性限制任何控制器Autorize:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
Run Code Online (Sandbox Code Playgroud)
AllowAnonymous如果在应用程序级别应用授权筛选器,请使用属性.
原始答案: 来自文档
添加
[AllowAnonymous]到家庭控制器,以便匿名用户可以在注册之前获取有关该站点的信息.Run Code Online (Sandbox Code Playgroud)using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; namespace ContactManager.Controllers { [AllowAnonymous] public class HomeController : Controller { public IActionResult Index() { return View(); }