Skip to content

Commit

Permalink
refactor: 更新登录逻辑支持 returnUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
ArgoZhang committed Feb 25, 2025
1 parent 8abd36a commit 602c50d
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { execute } from "../../_content/BootstrapBlazor/modules/ajax.js"

export async function login(url, userName, rememberMe) {
var password = document.querySelector('input[type="password"]').value;
await execute({
const password = document.querySelector('input[type="password"]').value;
const response = await execute({
url: url,
method: 'POST',
toJson: false,
Expand All @@ -12,5 +12,7 @@ export async function login(url, userName, rememberMe) {
rememberMe
}
});
location.href = "/";
if (response.redirected) {
window.location.href = response.url;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace BootstrapAdmin.Web.Components.Pages.Admin;

/// <summary>
///
/// Index 组件
/// </summary>
[AllowAnonymous]
public partial class Index
Expand Down
62 changes: 46 additions & 16 deletions src/blazor/admin/BootstrapAdmin.Web/Components/Pages/Home/Index.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
// Website: https://pro.blazor.zone

using BootstrapAdmin.Web.Components.Layout;
using BootstrapAdmin.Web.Core;
using BootstrapAdmin.Web.Services;
using BootstrapAdmin.Web.Utils;
using Microsoft.AspNetCore.Authorization;
using System.Reflection;
using Microsoft.AspNetCore.Components.Authorization;

namespace BootstrapAdmin.Web.Pages.Home;

/// <summary>
/// 返回前台页面
/// </summary>
[Route("")]
[Route("Home")]
[Route("Index")]
[Route("Home/Index")]
[Route("/")]
[Route("/Home")]
[Route("/Home/Index")]
[Authorize]
[Layout(typeof(LoginLayout))]
public class Index : ComponentBase
{
/// <summary>
///
/// </summary>
[SupplyParameterFromQuery]
[Parameter]
public string? ReturnUrl { get; set; }

/// <summary>
///
/// </summary>
[SupplyParameterFromQuery]
[Parameter]
public string? AppId { get; set; }

[Inject]
[NotNull]
private NavigationManager? Navigation { get; set; }
Expand All @@ -36,18 +51,37 @@ public class Index : ComponentBase
[NotNull]
private IUser? UsersService { get; set; }

[Inject]
[NotNull]
private AuthenticationStateProvider? AuthenticationStateProvider { get; set; }

[Inject]
[NotNull]
private string? Url { get; set; }
private NavigationManager? NavigationManager { get; set; }

private bool _render = true;

/// <summary>
/// <inheritdoc/>
/// </summary>
protected override void OnInitialized()
/// <returns></returns>
protected override async Task OnParametersSetAsync()
{
// 查看是否自定义前台
Url = LoginHelper.GetDefaultUrl(Context, null, null, UsersService, DictsService);
_render = false;
await base.OnParametersSetAsync();

var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
Context.UserName = state.User.Identity?.Name;
Context.BaseUri = NavigationManager.ToAbsoluteUri(NavigationManager.BaseUri);
_render = true;
}

/// <summary>
/// <inheritdoc/>
/// </summary>
/// <returns></returns>
protected override bool ShouldRender() => _render;

/// <summary>
/// <inheritdoc/>
/// </summary>
Expand All @@ -56,12 +90,8 @@ protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
var routes = GetType().GetCustomAttributes<RouteAttribute>();
if (routes.Any(i => $"{Navigation.BaseUri}{i.Template}".TrimEnd('/').Equals(Url, StringComparison.OrdinalIgnoreCase)))
{
Url = "Admin/Index";
}
var url = LoginHelper.GetDefaultUrl(Context, ReturnUrl, AppId, UsersService, DictsService);
Navigation.NavigateTo(url);
}
Navigation.NavigateTo(Url, true);
}
}
27 changes: 17 additions & 10 deletions src/blazor/admin/BootstrapAdmin.Web/Controllers/LoginController.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
// Website: https://pro.blazor.zone

using BootstrapAdmin.Web.Core;
using BootstrapAdmin.Web.Models;
using BootstrapAdmin.Web.Services;
using BootstrapAdmin.Web.Services.SMS;
using BootstrapAdmin.Web.Utils;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
Expand Down Expand Up @@ -36,7 +35,7 @@ public class LoginController : Controller
/// <param name="dictService"></param>
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<RedirectResult> Login([FromBody] LoginModel model,
public async Task<ActionResult> Login([FromBody] LoginModel model,
[FromQuery] string? returnUrl, [FromQuery] string? appId,
[FromServices] BootstrapAppContext context,
[FromServices] IUser userService,
Expand All @@ -50,6 +49,11 @@ public async Task<RedirectResult> Login([FromBody] LoginModel model,
}

var auth = userService.Authenticate(userName, password);
if (auth == false)
{
return RedirectLogin();
}

var persistent = model.RememberMe;
var period = 0;
if (persistent)
Expand All @@ -60,12 +64,10 @@ public async Task<RedirectResult> Login([FromBody] LoginModel model,

context.UserName = userName;
context.BaseUri = new Uri($"{Request.Scheme}://{Request.Host}/");
return auth
? await SignInAsync(userName, LoginHelper.GetDefaultUrl(context, returnUrl, appId, userService, dictService), persistent, period)
: RedirectLogin(returnUrl);
return await SignInAsync(userName, returnUrl, appId, persistent, period);
}

private async Task<RedirectResult> SignInAsync(string userName, string returnUrl, bool persistent, int period = 0, string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme)
private async Task<LocalRedirectResult> SignInAsync(string userName, string? returnUrl, string? appId, bool persistent, int period = 0, string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme)
{
var identity = new ClaimsIdentity(authenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, userName));
Expand All @@ -80,8 +82,8 @@ private async Task<RedirectResult> SignInAsync(string userName, string returnUrl
properties.ExpiresUtc = DateTimeOffset.Now.AddDays(period);
}
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);

return Redirect(returnUrl);
var url = string.IsNullOrEmpty(appId) ? "/Admin/Index" : $"/Home/Index?ReturnUrl={returnUrl}&AppId={appId}";
return LocalRedirect(url);
}

private RedirectResult RedirectLogin(string? returnUrl = null)
Expand Down Expand Up @@ -135,6 +137,11 @@ public async Task<IActionResult> Mobile(string phone, string code, [FromQuery] s
}

var auth = provider.Validate(phone, code);
if (auth == false)
{
return RedirectLogin();
}

var persistent = remember == "true";
var period = 0;
if (persistent)
Expand All @@ -149,7 +156,7 @@ public async Task<IActionResult> Mobile(string phone, string code, [FromQuery] s

context.UserName = phone;
context.BaseUri = new Uri(Request.Path.Value!);
return auth ? await SignInAsync(phone, LoginHelper.GetDefaultUrl(context, returnUrl, appId, userService, dictService), persistent, period, MobileSchema) : RedirectLogin(returnUrl);
return await SignInAsync(phone, returnUrl, appId, persistent, period, MobileSchema);
}

#endregion
Expand Down
30 changes: 15 additions & 15 deletions src/blazor/admin/BootstrapAdmin.Web/Utils/LoginHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
// Website: https://pro.blazor.zone

using BootstrapAdmin.Web.Core;
using BootstrapAdmin.Web.Services;
Expand All @@ -23,32 +23,32 @@ public static class LoginHelper
/// <returns></returns>
public static string GetDefaultUrl(BootstrapAppContext context, string? returnUrl, string? appId, IUser userService, IDict dictService)
{
if (string.IsNullOrEmpty(returnUrl))
if (string.IsNullOrEmpty(appId))
{
// 查找 User 设置的默认应用
var userName = context.UserName;
var defaultAppId = context.AppId;
var schema = context.BaseUri.Scheme;
var host = context.BaseUri.Host;
appId ??= userService.GetAppIdByUserName(userName) ?? defaultAppId;

appId = userService.GetAppIdByUserName(userName) ?? defaultAppId;
if (appId == defaultAppId && dictService.GetEnableDefaultApp())
{
// 开启默认应用
appId = dictService.GetApps().FirstOrDefault(d => d.Key != defaultAppId).Key;
}
}
return context.FormatUrl(returnUrl, appId, dictService);
}

if (!string.IsNullOrEmpty(appId))
{
var appUrl = dictService.GetHomeUrlByAppId(appId);
if (!string.IsNullOrEmpty(appUrl))
{
returnUrl = string.Format(appUrl, schema, host).TrimEnd('/');
}
}
private static string FormatUrl(this BootstrapAppContext context, string? returnUrl, string? appId, IDict dictService)
{
if (string.IsNullOrEmpty(appId))
{
return "Admin/Index";
}

return returnUrl ?? "/Admin/Index";
var url = dictService.GetHomeUrlByAppId(appId);
return string.IsNullOrEmpty(url)
? "Admin/Index"
: $"{string.Format(url, context.BaseUri.Scheme, context.BaseUri.Host)}{returnUrl}";
}

/// <summary>
Expand Down

0 comments on commit 602c50d

Please sign in to comment.