我有一个具有ASP.NET Core Identity的现有ASP.NET Core MVC应用程序,在该应用程序中,我使用signInManager.PasswordSignInAsync
和[Authorize]
属性的组合来强制用户登录到网站,并具有一定的作用。在本地和Azure WebApp中运行良好。
现在,我想将应用程序的预览版发布到另一个Azure WebApp。这次,我希望每个访问者在显示网站上的任何内容之前输入另一组凭据。我想我想要类似.htaccess / BasicAuthenication的东西。但是,在用户输入第一组凭据之后,不应登录,因为他需要使用常规的登录程序(就像在实时版本中一样,该版本可以公开访问,但是其中某些页面要求用户登录)。基本上,我只想在不影响当前现有身份验证的基础上再增加一层密码保护。
鉴于我想允许使用预览密码的任何人访问,以下解决方案似乎不适用于我的情况:
有没有简单的方法,例如在Startup类中添加两行代码来实现所需的第二级密码保护?
您可以通过基本身份验证来进行第二次身份验证,这很简单,并且不需要太多代码。您将需要一个中间件,该中间件将在原始身份验证完成后进行拦截/调用
中间件
public class SecondaryBasicAuthenticationMiddleware : IMiddleware
{
//CHANGE THIS TO SOMETHING STRONGER SO BRUTE FORCE ATTEMPTS CAN BE AVOIDED
private const string UserName = "TestUser1";
private const string Password = "TestPassword1";
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
//Only do the secondary auth if the user is already authenticated
if (!context.User.Identity.IsAuthenticated)
{
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic "))
{
// Get the encoded username and password
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
// Decode from Base64 to string
var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
// Split username and password
var username = decodedUsernamePassword.Split(':', 2)[0];
var password = decodedUsernamePassword.Split(':', 2)[1];
// Check if login is correct
if (IsAuthorized(username, password))
{
await next.Invoke(context);
return;
}
}
// Return authentication type (causes browser to show login dialog)
context.Response.Headers["WWW-Authenticate"] = "Basic";
// Return unauthorized
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
await next.Invoke(context);
}
}
//If you have a db another source you want to check then you can do that here
private bool IsAuthorized(string username, string password) =>
UserName == username && Password == password;
}
在启动时->配置(确保在现有的身份验证和授权之后添加此名称)
//Enable Swagger and SwaggerUI
app.UseMiddleware<SecondaryBasicAuthenticationMiddleware>(); //can turn this into an extension if you wish
app.UseAuthentication();
app.UseAuthorization();
在启动-> ConfigureServices中注册中间件
services.AddTransient<SecondaryBasicAuthenticationMiddleware>();
chrome应该像这样弹出一个基本的身份验证对话框
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句