Skip to content

Commit

Permalink
feat:add authorization for imaotai web and wpf
Browse files Browse the repository at this point in the history
  • Loading branch information
bingtianyiyan committed Jul 23, 2024
1 parent b69b6f5 commit 316e5da
Show file tree
Hide file tree
Showing 23 changed files with 233 additions and 222 deletions.
3 changes: 3 additions & 0 deletions IMaoTai.Core/CommonX.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public class CommonX
//登录用户账号缓存
public static string LoginUserListFile = Path.Combine(CacheDir, "loginUserList.json");

//登录账户session缓存(wpf)
public static string LoginCacheUserListFile = Path.Combine(CacheDir, "loginCacheUserList.json");

/// <summary>
/// 订单数据库表名
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions IMaoTai.Core/IMaoTai.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="FreeSql" Version="3.2.698" />
<PackageReference Include="FreeSql.Provider.MySql" Version="3.2.698" />
<PackageReference Include="FreeSql.Provider.Sqlite" Version="3.2.698" />
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="7.0.20" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
Expand Down
5 changes: 3 additions & 2 deletions IMaoTai.MasaBlazor/Components/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
<link rel="stylesheet" href="IMaoTai.MasaBlazor.styles.css" />
<link href="css/materialdesign/v7.1.96/css/materialdesignicons.min.css" rel="stylesheet">
<link rel="icon" type="image/png" href="favicon.png" />
<HeadOutlet @rendermode="@InteractiveServer" />
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
</head>

<body>
<Routes @rendermode="@InteractiveServer" />
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<script src="_framework/blazor.web.js"></script>
<script src="_content/Masa.Blazor/js/masa-blazor.js"></script>
<script src="https://cdn.masastack.com/npm/echarts/5.1.1/echarts.min.js"></script>
</body>

</html>
7 changes: 5 additions & 2 deletions IMaoTai.MasaBlazor/Helpers/IocHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Yitter.IdGenerator;
using IMaoTai.MasaUI.Core;
using Microsoft.AspNetCore.Components.Authorization;
using Blazored.LocalStorage;

namespace IMaoTai.MasaBlazor.Web.Helpers;

Expand All @@ -19,9 +20,11 @@ public static class IocHelper
public static IServiceCollection RegisterService(IServiceCollection _services)
{
_services.AddAuthorizationCore();
_services.AddCascadingAuthenticationState();
_services.AddScoped<HostAuthenticationStateProvider>();
_services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<HostAuthenticationStateProvider>());

_services.AddScoped<AuthenticationStateProvider, HostAuthenticationStateProvider>();
_services.AddBlazoredLocalStorage(config =>
config.JsonSerializerOptions.WriteIndented = true);
_services.TryAddSingleton<IUserService, UserService>();
_services.TryAddSingleton<IAppointProjectService, AppointProjectService>();
_services.TryAddSingleton<IShopService, ShopService>();
Expand Down
14 changes: 12 additions & 2 deletions IMaoTai.MasaBlazor/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@
builder.Services.AddMasaBlazor();

await IocHelper.InitBusiness();
builder.Services.AddAdminCaviar(new Type[] { typeof(Program), typeof(IMaoTai.MasaUI._Imports) });
builder.Services.AddIMaoTaiAdmin(new Type[] { typeof(Program), typeof(IMaoTai.MasaUI._Imports) });

//Ôö¼ÓAPIÔÊÐí¿çÓòµ÷ÓÃ
builder.Services.AddCors(options => options.AddPolicy("Any",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(_ => true)
.AllowCredentials();
}));

var app = builder.Build();

Expand All @@ -24,7 +34,7 @@
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}

app.UseCors("Any");
app.UseStaticFiles();
app.UseAntiforgery();

Expand Down
33 changes: 8 additions & 25 deletions IMaoTai.MasaBlazor/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,29 +1,12 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56107",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5004",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"profiles": {
"IMaoTai.MasaBlazor": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
"applicationUrl": "http://localhost:5004;https://localhost:5005"
}
}
}
12 changes: 1 addition & 11 deletions IMaoTai.MasaUI/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,8 @@ public static bool IsServer
/// </summary>
public static List<Assembly> AdditionalAssemblies;

public static WebAssemblyHostBuilder AddCavWasm(this WebAssemblyHostBuilder builder)
{
//IsServer = false;
//builder.Services.AddScoped<IAuthService, WasmAuthService>();
builder.Services.AddOptions();
//builder.Services.AddAuthorizationCore();
//builder.Services.AddSingleton<IAuthorizationPolicyProvider, DefaultAuthorizationPolicyProvider>();
//builder.Services.AddSingleton<IAuthorizationService, DefaultAuthorizationService>();
return builder;
}

public static IServiceCollection AddAdminCaviar(this IServiceCollection services, Type[] assemblies)
public static IServiceCollection AddIMaoTaiAdmin(this IServiceCollection services, Type[] assemblies)
{
if (assemblies != null)
{
Expand Down
65 changes: 26 additions & 39 deletions IMaoTai.MasaUI/Core/HostAuthenticationStateProvider.cs
Original file line number Diff line number Diff line change
@@ -1,69 +1,55 @@
// Copyright (c) BeiYinZhiNian (1031622947@qq.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: http://www.caviar.wang/ or https://gitee.com/Cherryblossoms/caviar.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using IMaoTai.Core.Domain;
using IMaoTai.Core.Service;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;

namespace IMaoTai.MasaUI.Core
{
public class HostAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ILoginUserService _loginUserService;
private ProtectedSessionStorage _protectedSessionStore;

//private CurrentUser _currentUser;
private ClaimsIdentity identity = new ClaimsIdentity();

public HostAuthenticationStateProvider(ILoginUserService loginUserService)
public HostAuthenticationStateProvider(
ILoginUserService loginUserService,
ProtectedSessionStorage protectedSessionStore)
{
_loginUserService = loginUserService;
_protectedSessionStore = protectedSessionStore;
}

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var userSessionStorageResult = await _protectedSessionStore.GetAsync<UserLogin>("UserSession");
var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null;
if (userSession != null)
{
var claims = new[] {
new Claim(ClaimTypes.Name, userSession.UserName)};
identity = new ClaimsIdentity(claims,"IMaoTai");
}
var user = new ClaimsPrincipal(identity);
return new AuthenticationState(new ClaimsPrincipal(identity));
//var identity = new ClaimsIdentity();
//try
//{
// var userInfo = await GetCurrentUser();
// if (userInfo.IsAuthenticated)
// {
// var claims = new[] { new Claim(ClaimTypes.Name, _currentUser.UserName) };
return await Task.FromResult( new AuthenticationState(user));

// identity = new ClaimsIdentity(claims, nameof(HostAuthenticationStateProvider));
// }
//}
//catch (HttpRequestException ex)
//{
// Console.WriteLine("Request failed:" + ex.ToString());
//}

//var user = new ClaimsPrincipal(identity);
//return new AuthenticationState(new ClaimsPrincipal(identity));

}

//public async Task<CurrentUser> GetCurrentUser()
//{
// if (_currentUser != null && _currentUser.IsAuthenticated) return _currentUser;
// _currentUser = await _loginUserService.CurrentUserInfo();
// //_currentUser = new CurrentUser()
// //{
// // UserName = "admin",
// // IsAuthenticated = true,
// //};
// return _currentUser;
//}

public ClaimsPrincipal GetCurrentUser()
{
var user = new ClaimsPrincipal(identity);
return user;
}

public async Task<string> Logout()
{
var result = await _loginUserService.Logout();
// _currentUser = null;
identity = new ClaimsIdentity();
if (!Config.IsServer)
{
Expand All @@ -79,6 +65,7 @@ public async Task<bool> Login(UserLogin loginParameters, string returnUrl)
{
var claims = new[] { new Claim(ClaimTypes.Name, loginParameters.UserName) };
identity = new ClaimsIdentity(claims, "IMaoTai");
await _protectedSessionStore.SetAsync("UserSession", loginParameters);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
return result;
Expand Down
95 changes: 95 additions & 0 deletions IMaoTai.MasaUI/Core/WHostAuthenticationStateProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using IMaoTai.Core.Domain;
using IMaoTai.Core.Service;
using JsonFlatFileDataStore;
using IMaoTai.Core;

namespace IMaoTai.MasaUI.Core
{
public class WHostAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ILoginUserService _loginUserService;

private ClaimsIdentity identity = new ClaimsIdentity();

public WHostAuthenticationStateProvider(
ILoginUserService loginUserService)
{
_loginUserService = loginUserService;
}

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// Open database (create new if file doesn't exist)
var store = new DataStore(CommonX.LoginCacheUserListFile);
// Get employee collection
var collection = store.GetCollection<UserLogin>();

// Find item with name
var userSession = collection
.AsQueryable()
.FirstOrDefault();

if (userSession != null)
{
var claims = new[] {
new Claim(ClaimTypes.Name, userSession.UserName)};
identity = new ClaimsIdentity(claims, "IMaoTai");
}
var user = new ClaimsPrincipal(identity);
return await Task.FromResult( new AuthenticationState(user));

}


public ClaimsPrincipal GetCurrentUser()
{
var user = new ClaimsPrincipal(identity);
return user;
}

public async Task<string> Logout()
{
var result = await _loginUserService.Logout();
identity = new ClaimsIdentity();
if (!Config.IsServer)
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
return result;
}

public async Task<bool> Login(UserLogin loginParameters, string returnUrl)
{
var result = await _loginUserService.Login(loginParameters, returnUrl);
if (result)
{
var claims = new[] { new Claim(ClaimTypes.Name, loginParameters.UserName) };
identity = new ClaimsIdentity(claims, "IMaoTai");

// Open database (create new if file doesn't exist)
var store = new DataStore(CommonX.LoginCacheUserListFile);
// Get employee collection
var collection = store.GetCollection<UserLogin>();

// Find item with name
var userDynamic = collection
.AsQueryable()
.FirstOrDefault(p => p.UserName == loginParameters.UserName);
if (userDynamic == null)
{
await collection.InsertOneAsync(loginParameters);
}
else
{
await collection.UpdateOneAsync(p => p.UserName == loginParameters.UserName, loginParameters);
}


NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
return result;
}
}
}
1 change: 1 addition & 0 deletions IMaoTai.MasaUI/IMaoTai.MasaUI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
<PackageReference Include="Masa.Blazor" Version="1.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="7.0.20" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="7.0.20" />
Expand Down
1 change: 0 additions & 1 deletion IMaoTai.MasaUI/NoAuthorizeRoutes.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
AdditionalAssemblies="Config.AdditionalAssemblies">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(Shared.MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<IMaoTai.MasaUI.Shared._404></IMaoTai.MasaUI.Shared._404>
Expand Down
3 changes: 0 additions & 3 deletions IMaoTai.MasaUI/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
@using Masa.Blazor
@using IMaoTai.MasaUI.Core
@inherits AuthComponentBase
<head>
<script src="https://cdn.masastack.com/npm/echarts/5.1.1/echarts.min.js"></script>
</head>

<MImage AspectRatio="16/9d" Width="@("100%")" Height="311"
Src="/imgs/home.png"></MImage>
Expand Down
1 change: 0 additions & 1 deletion IMaoTai.MasaUI/Pages/InstructionsData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

@code {



}

5 changes: 0 additions & 5 deletions IMaoTai.MasaUI/Pages/LogData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,6 @@ else
await GetListDataFromApi();
}

protected override async Task OnInitializedAsync()
{
await GetListDataFromApi();
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
Expand Down
Loading

0 comments on commit 316e5da

Please sign in to comment.