ASP.NET核心Web API跳过身份验证
问题描述:
我正在使用自定义基本身份验证,基于以下示例编写ASP.NET核心Web应用程序: ASP.NET Core Web API Authentication 现在,我在我的用户控制器中执行一项操作以注册用户。所以我想通过这个方法我的自定义属性“SkipAuthAttribute”来说,如果有人调用这个方法(动作),你必须跳过认证(希望注册的用户,没有登录)。ASP.NET核心Web API跳过身份验证
但类型的HttpContext没有ActionDescriptor获得行动
的朋友里有人的自定义属性,我如何通过一些具体行动跳过authenticaion?
答
最后回答: 您应该尝试根据框架编写代码。来自示例的中间件不适用于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>();
。如果你申请授权应用层过滤
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
和使用属性AllowAnonymous
:有了这个代码,您可以限制使用非标准属性Autorize
任何控制器。
原来的答复: 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。在我的情况下,基本身份验证是一个自定义的中间件(请参阅示例https://*.com/questions/38977088/asp-net-core-web-api-authentication)。因此它不关心AllowAnonymous属性。我想阅读被调用的控制器的属性。 –
ASP.Net Core与MVC和Web API相同。 –
它适合我!谢谢!!! – Leila