ASP.NET Core 5 Google认证时自定义跳转自有登录页面的问题咨询
解决方案
1. 调整Startup.cs 认证服务配置
问题根源是当前配置将Google认证设为了默认挑战方案,未授权请求会直接触发Google登录跳转。修改认证配置将Cookie认证设为默认方案,同时指定自定义登录页路径:
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { // 统一将Cookie认证设为默认的认证、挑战、禁止方案 options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { // 配置未授权时跳转的自定义登录页路径 options.LoginPath = "/Login"; // 可选:配置权限不足时的跳转页 options.AccessDeniedPath = "/AccessDenied"; }) .AddGoogle(options => { // 保留你原有的Google认证配置,包括ClientId、ClientSecret等 options.ClientId = "你的Google应用ClientId"; options.ClientSecret = "你的Google应用ClientSecret"; // 回调路径保持默认或自定义即可,无需修改 options.CallbackPath = "/signin-google"; }); // 其余服务配置保持不变 services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 其余中间件配置保持不变,注意中间件顺序不能乱 app.UseRouting(); // 注意必须先加认证中间件,再加授权中间件 app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
2. 新增Google登录触发接口
在LoginController中添加主动触发Google认证的Action,供自定义登录页的Google按钮调用:
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Google; [AllowAnonymous] public IActionResult TriggerGoogleLogin() { var properties = new AuthenticationProperties { // 配置Google登录成功后跳转回的地址,这里示例跳回首页 RedirectUri = Url.Action("Index", "Home") }; // 显式指定使用Google认证方案发起挑战 return Challenge(properties, GoogleDefaults.AuthenticationScheme); }
3. 自定义登录页添加Google登录入口
在Login页的视图代码中添加跳转按钮即可:
<a asp-action="TriggerGoogleLogin" asp-controller="Login">使用Google账号登录</a>
调整后访问带[Authorize]特性的受限路由时,会优先跳转到你配置的/Login自定义登录页,用户可自主选择邮箱密码登录或Google登录。
内容的提问来源于stack exchange,提问作者Tran Phong
相关产品推荐
相关产品推荐

