简体   繁体   English

Asp.net 核心:托管具有相同身份验证的 MVC 和 SPA。 重定向到应用程序的 MVC 部分时客户端被注销

[英]Asp.net core: hosting MVC and SPA with same Identity authentication. Client gets logged out when redirecting to MVC part of application

Im using the default asp.net core + angular scaffold with identity to host my SPA inside of a MVC application, the authentication part works as it should inside of the angular SPA.我使用带有身份的默认 asp.net 核心 + angular 脚手架将我的 SPA 托管在 MVC 应用程序内部,身份验证部分在 angular 内部正常工作。

My startup.cs is nothing special, standard .net core scaffold stuff:我的 startup.cs 没什么特别的,标准的 .net 核心脚手架的东西:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DbName")));

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddRazorPages();
            services.AddHttpContextAccessor();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                }
            });
        }
    }

I also serve razor views via .net core controllers for a different part of the application, however the scaffollded authentication does not work here at all.我还通过 .net 核心控制器为应用程序的不同部分提供 razor 视图,但是脚手架式身份验证在这里根本不起作用。

Here is what happens currently:这是当前发生的情况:

  1. Go to adress, protected angular router guard redirect me to scaffolded login page. Go 到地址,受保护的 angular 路由器保护将我重定向到脚手架登录页面。
  2. I login and get redirected to the SPA.'我登录并被重定向到 SPA。

When I "path traverse" out of the SPA the problem occurs:当我“路径遍历”出 SPA 时,会出现问题:

  1. I go to: http://myadress/mycontroller/MyAction) I get logged out of the application and using a simple controller with a UserManager<ApplicationUser> I check if the HttpContext.User exists:我 go 到:http://myadress/mycontroller/MyAction)我退出应用程序并使用简单的 controller 和检查用户是否存在: UserManager<ApplicationUser>
        public IActionResult MyAction()
        {
            //user cannot be found here.
            var user = _userManager.GetUserAsync(HttpContext.User);
            
            return View();
        }

I tried putting a [Authorize] thinking a redirect to the login page again should help me get logged into the "Mvc part" of the app.我尝试放置一个[Authorize]认为再次重定向到登录页面应该可以帮助我登录到应用程序的“Mvc 部分”。 (since earlier I logged in with a redirectURL to the SPA), but no succes: I get a 401 upon visiting without any more information. (因为之前我使用重定向 URL 登录到 SPA),但没有成功:我在没有任何更多信息的情况下访问时收到 401。

The desired outcome I have with this whole debacle is as follows:我对整个崩溃的期望结果如下:

  • 2 parts of an application hosted in asp.net core;托管在 asp.net 内核中的应用程序的 2 部分; 1 is your standard MVC app with razor views (admin only) and the other a SPA in angular for clients (client only). 1 是您的标准 MVC 应用程序,带有 razor 视图(仅限管理员),另一个是 angular 中用于客户端的 SPA(仅限客户端)。
  • once A user logs in, he/she gets redirected based on role the right part of the app, so /dashboard for admins (MVC) and /app for clients (angular)一旦用户登录,他/她会根据应用程序右侧的角色被重定向,因此 /dashboard for admins (MVC) 和 /app for clients (angular)

This is basically it, I dont think this should be that difficult but im pretty new to asp.net core.基本上就是这样,我认为这应该不是那么困难,但我对 asp.net 内核还很陌生。

I hope I have given enough information, any help is appreciated.我希望我已经提供了足够的信息,任何帮助表示赞赏。

You will need to share the same stateless authorisation cookie between MVC, web API and the SPA.您将需要在 MVC、web API 和 SPA 之间共享相同的无状态授权 cookie。

I suggest using a .NET HttpOnly cookie.我建议使用 .NET HttpOnly cookie。

When the SPA initially loads, you can query the Web API for the user permissions.当 SPA 初始加载时,您可以查询 Web API 以获取用户权限。 If the cookie exists it will be sent through with the request and you can return the user permissions, otherwise return nothing - which indicates the user is not logged in.如果 cookie 存在,它将与请求一起发送,您可以返回用户权限,否则不返回任何内容 - 表示用户未登录。

I have successfully done this using a React SPA + Core Web API for admin and Core MVC for a Server Side Rendered front-end.我已经成功地使用了 React SPA + Core Web API 用于管理员和 Core MVC 用于服务器端渲染前端。

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

相关问题 Asp.net 核心 MVC 应用程序与 Azure AD 身份验证。 无法取消保护浏览器后退按钮上的消息 state - Asp.net Core MVC application with Azure AD authentication. Unable to unprotect message state on browser back button 注销并返回网址 | ASP.Net 核心标识 MVC | 验证 - Logout & ReturnUrl | ASP.Net Core Identity MVC | Authentication 防止在启动后重定向 ASP.NET Core MVC 应用程序 - Prevent redirecting ASP.NET Core MVC Application after start ASP.NET MVC中的身份cookie身份验证 - Identity cookie authentication in ASP.NET MVC 用户注销时的ASP.NET MVC显示消息 - ASP.NET MVC Display message when user is logged out 将ASP.NET MVC Core应用程序的[部分]发布到Web主机 - Publishing [part] of ASP.NET MVC Core application to web host ASP.NET核心MVC MySQL身份 - ASP.NET Core MVC MySQL Identity Asp.Net MVC核心和身份3 - Asp.Net MVC Core and Identity 3 .Net Core 3.1 MVC 身份验证个人用户帐户和 ASP.NET 核心项目中的脚手架身份 - .Net Core 3.1 MVC Authentication Individual User Accounts and Scaffold Identity in ASP.NET Core projects ASP.NET 核心 MVC 身份 - 如何查看当前登录的用户? - ASP.NET Core MVC Identity - how to get current logged in user in view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM