简体   繁体   English

此外,密码保护作为 Azure WebApp 托管的 ASP.NET Core MVC 网站和现有身份验证

[英]Additionally password protect an ASP.NET Core MVC website hosted as Azure WebApp with existing authentication

I have an existing ASP.NET Core MVC application with ASP.NET Core Identity where I use a combination of signInManager.PasswordSignInAsync and [Authorize] attributes to enforce that a user is logged in to website, has a certain role et cetera.我有一个现有的 ASP.NET 核心 MVC 应用程序和 ASP.NET 核心标识,我使用signInManager.PasswordSignInAsync[Authorize]属性的组合来强制用户登录到网站,具有特定的角色等等。 This works fine locally and in an Azure WebApp.这在本地和 Azure WebApp 中都可以正常工作。

Now, I want to publish a preview version of my application to another Azure WebApp.现在,我想将我的应用程序的预览版发布到另一个 Azure WebApp。 This time, I want each visitor to enter another set of credentials before anything from the website is being shown.这一次,我希望每个访问者在显示网站上的任何内容之前输入另一组凭据。 I guess I'd like to have something like an .htaccess / BasicAuthenication equivalent.我想我想要一个类似 .htaccess / BasicAuthenication 的东西。 However, after a user entered the first set of credentials, he should not be logged in since he should need to use the normal login prodecure (just as in the live version which is publicly accessible but this has certain pages which require the user to be logged in).但是,在用户输入第一组凭据后,他不应该登录,因为他应该需要使用正常的登录过程(就像在可公开访问的实时版本中一样,但是这有某些页面需要用户登录)。 Basically, I just want to add another layer of password protection on top without impacting the currently existing authentication .基本上,我只想在不影响当前存在的身份验证的情况下在顶部添加另一层密码保护。

Given that I want allow access to anyone with the preview password, the following solutions do not seem to work in my case:鉴于我想允许任何拥有预览密码的人访问,以下解决方案在我的情况下似乎不起作用:

  • Limit the access to the WebApp as a firewall setting.限制对 WebApp 的访问作为防火墙设置。 The client IPs will not be from a certain IP range and they will be dynamically assigned by their ISP.客户端 IP 不会来自某个 IP 范围,它们将由其 ISP 动态分配。
  • Use an individual user account with Azure AD in front.使用前面带有 Azure AD 的个人用户帐户。 This might be my fallback (although I'm not sure on how to implement exactly) but I'd rather not have another set of individual user credentials to take care.这可能是我的后备方案(尽管我不确定如何准确实施),但我宁愿没有另一组个人用户凭据来照顾。 The credentials could even be something as simple as preview // preview.凭据甚至可以像预览//预览一样简单。

Is there a simple way like adding two lines of codes in the Startup class to achieve my desired second level of password protection?有没有一种简单的方法,比如在 Startup class 中添加两行代码来实现我想要的二级密码保护?

You can do a second auth via a basic auth, something simple and not too much code.您可以通过基本身份验证进行第二次身份验证,这是一些简单且代码不多的事情。 You will need a middleware that will intercept/called after the original authentication is done您将需要一个中间件,在原始身份验证完成后拦截/调用

Middleware中间件

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;
}

In startup -> Configure (make sure you add this after your existing authentication and authorization)在启动时 -> 配置(确保在现有的身份验证和授权之后添加它)

    //Enable Swagger and SwaggerUI
    app.UseMiddleware<SecondaryBasicAuthenticationMiddleware>(); //can turn this into an extension if you wish

    app.UseAuthentication();
    app.UseAuthorization();        

In Startup -> ConfigureServices register the middleware在 Startup -> ConfigureServices 注册中间件

services.AddTransient<SecondaryBasicAuthenticationMiddleware>();

And chrome should pop up a basic auth dialog like this chrome应该会弹出一个像这样的基本身份验证对话框

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure ASP.NET 核心 MVC WebApp 的 AD 身份验证 - 如何自定义应用程序的 Redirect_URI! 发送 - Azure AD Authentication for ASP.NET Core MVC WebApp - how to customize the Redirect_URI the APPLICATION! sends Azure 部署后 ASP.NET Core MVC webapp 错误 - ASP.NET Core MVC webapp error after Azure deployment Azure AD 身份验证对现有 ASP.NET 核心身份应用程序 - Azure AD authentication to existing ASP.NET Core Identity application 在 ASP.NET Core WebApp 上提供持久配置托管在 IIS - Provide persistent configuration on ASP.NET Core WebApp Hosted on IIS 在Asp.Net Core(MVC)的现有项目中将身份验证从无身份验证更改为个人身份验证 - Change authentication from no authentication to individual authentication in existing project of Asp.Net Core (MVC) asp.net核心mvc密码验证器 - asp.net core mvc password validators 通过 ASP.NET 内核上的身份验证保护 Static 文件 - Protect Static Files with Authentication on ASP.NET Core ASP.NET MVC 5 中的 Azure AD 身份验证 - Azure AD authentication in ASP.NET MVC 5 使用 asp.net core mvc 中的身份验证保护 wwwroot 中的某些文件夹 - Protect certain folders in wwwroot with authetication in asp.net core mvc Azure 应用服务上的 ASP.NET Core MVC Azure AD 身份验证循环 - ASP.NET Core MVC Azure AD Authentication Loop on Azure App Service
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM