【发布时间】:2021-05-20 05:55:32
【问题描述】:
我正在编写一个在 .Net 5.0 上运行的 Razor Pages 应用程序。此应用程序需要能够支持工作人员(使用 Windows 身份验证登录)和申请人(没有 Windows 帐户,因此需要使用自定义身份验证过程注册/登录)。我可以让 Windows auth 或自定义 auth 工作,但两者不想一起玩!!
我相信我需要编写IAuthenticationService 的自定义实现,但这就是让我绊倒的地方。我不知道在ChallengeAsync 中我需要做什么才能让挑战通过!
这是目前的 AuthService 实现(是的,它不是最好的,但我现在的重点是让它工作!!):
public class AuthService : IAuthenticationService
{
async Task<AuthenticateResult> IAuthenticationService.AuthenticateAsync(HttpContext context, string scheme)
{
if (HasAnonymousAttribute(context))
{
return AuthenticateResult.NoResult();
}
var user = getUser(context);
if (user != null)
{
var ticket = new AuthenticationTicket(user, "magic");
return AuthenticateResult.Success(ticket);
}
await context.ChallengeAsync("Windows");
if (context.User.Identity.IsAuthenticated)
{
var ticket = new AuthenticationTicket(context.User, "Windows");
return AuthenticateResult.Success(ticket);
}
return AuthenticateResult.Fail("Please log in");
}
Task IAuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)
{
var user = context.Session.Get("User");
if (user == null)
{
//do something to block the user from access
}
return Task.FromResult(0);
}
Task IAuthenticationService.ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
Task IAuthenticationService.SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
{
if(scheme.ToLower() == "magic")
{
context.Session.Set("User", Encoding.ASCII.GetBytes(principal.Identity.Name));
}
return Task.FromResult(0);
}
Task IAuthenticationService.SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
private ClaimsPrincipal getUser(HttpContext context)
{
if (context.User.Identity.IsAuthenticated)
{
return (ClaimsPrincipal)context.User.Identity;
}
return null;
}
private bool HasAnonymousAttribute(HttpContext context)
{
var endpoint = context.GetEndpoint();
var retVal = (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null);
return retVal;
}
}
【问题讨论】:
标签: c# .net-core razor-pages