Blazor SSR/WASM IDS/OIDC 单点登录授权实例1-建立和配置IDS身份验证服务

本文主要是介绍Blazor SSR/WASM IDS/OIDC 单点登录授权实例1-建立和配置IDS身份验证服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录:

  1. OpenID 与 OAuth2 基础知识
  2. Blazor wasm Google 登录
  3. Blazor wasm Gitee 码云登录
  4. Blazor SSR/WASM IDS/OIDC 单点登录授权实例1-建立和配置IDS身份验证服务
  5. Blazor SSR/WASM IDS/OIDC 单点登录授权实例2-登录信息组件wasm
  6. Blazor SSR/WASM IDS/OIDC 单点登录授权实例3-服务端管理组件
  7. Blazor SSR/WASM IDS/OIDC 单点登录授权实例4 - 部署服务端/独立WASM端授权
  8. Blazor SSR/WASM IDS/OIDC 单点登录授权实例5 - Blazor hybird app 端授权
  9. Blazor SSR/WASM IDS/OIDC 单点登录授权实例5 - Winform 端授权

源码

BlazorOIDC/Server

1. 建立 BlazorOIDC 工程

新建wasm工程 BlazorOIDC

  • 框架: 7.0
  • 身份验证类型: 个人账户
  • ASP.NET Core 托管

2. 添加自定义身份实体类,扩展IDS字段

BlazorOIDC.Server项目

编辑 Models/WebAppIdentityUser.cs 文件

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;namespace BlazorOIDC.Server.Models;public class ApplicationUser : IdentityUser
{ /// <summary>/// Full name/// </summary>[Display(Name = "全名")][PersonalData]public string? Name { get; set; }/// <summary>/// Birth Date/// </summary>[Display(Name = "生日")][PersonalData]public DateTime? DOB { get; set; }[Display(Name = "识别码")]public string? UUID { get; set; }[Display(Name = "外联")]public string? provider { get; set; }[Display(Name = "税号")][PersonalData]public string? TaxNumber { get; set; }[Display(Name = "街道地址")][PersonalData]public string? Street { get; set; }[Display(Name = "邮编")][PersonalData]public string? Zip { get; set; }[Display(Name = "县")][PersonalData]public string? County { get; set; }[Display(Name = "城市")][PersonalData]public string? City { get; set; }[Display(Name = "省份")][PersonalData]public string? Province { get; set; }[Display(Name = "国家")][PersonalData]public string? Country { get; set; }[Display(Name = "类型")][PersonalData]public string? UserRole { get; set; }
}

3. 添加自定义声明

BlazorOIDC.Server项目

新建 Data/ApplicationUserClaimsPrincipalFactory.cs 文件

using BlazorOIDC.Server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;namespace Densen.Models.ids;public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{public ApplicationUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> role,IOptions<IdentityOptions> optionsAccessor) : base(userManager, role, optionsAccessor){}protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user){ClaimsIdentity claims = await base.GenerateClaimsAsync(user);var roles = await UserManager.GetRolesAsync(user);foreach (var role in roles){claims.AddClaim(new Claim("roleVIP", role));}return claims;}}

4. 配置文件

BlazorOIDC.Server项目

引用 Microsoft.EntityFrameworkCore.Sqlite 包, 示例使用sqlite数据库演示
引用第三方登录包

Microsoft.AspNetCore.Authentication.Facebook
Microsoft.AspNetCore.Authentication.Google
Microsoft.AspNetCore.Authentication.MicrosoftAccount
Microsoft.AspNetCore.Authentication.Twitter
AspNet.Security.OAuth.GitHub

编辑配置文件 appsettings.json, 添加连接字符串和第三方登录ClientId/ClientSecret等配置

{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-BlazorOIDC.Server-e292861d-0c29-45ea-84b1-b4558d5aa35d;Trusted_Connection=True;MultipleActiveResultSets=true","IdsSQliteConnection": "Data Source=../ids_api.db;"},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"IdentityServer": {"Clients": {"BlazorOIDC.Client": {"Profile": "IdentityServerSPA"}}},"AllowedHosts": "*","Authentication": {"Google": {"Instance": "https://accounts.google.com/o/oauth2/v2/auth","ClientId": "ClientId","ClientSecret": "ClientSecret","CallbackPath": "/signin-google"},"Facebook": {"AppId": "AppId","AppSecret": "AppSecret"},"Microsoft": {"ClientId": "ClientId","ClientSecret": "ClientSecret"},"Twitter": {"ConsumerAPIKey": "ConsumerAPIKey","ConsumerSecret": "ConsumerSecret"},"Github": {"ClientID": "ClientID","ClientSecret": "ClientSecret"},"WeChat": {"AppId": "AppId","AppSecret": "AppSecret"},"QQ": {"AppId": "AppId","AppKey": "AppKey"}}
}

5. 配置IDS身份验证服务

BlazorOIDC.Server项目

编辑 Program.cs 文件

using BlazorOIDC.Server.Data;
using BlazorOIDC.Server.Models;
using Densen.Identity.Areas.Identity;
using Densen.Models.ids;
using Duende.IdentityServer;
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;var builder = WebApplication.CreateBuilder(args);// Add services to the container.
//var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
//builder.Services.AddDbContext<ApplicationDbContext>(options =>
//    options.UseSqlServer(connectionString));//EF Sqlite 配置
builder.Services.AddDbContext<ApplicationDbContext>(o => o.UseSqlite(builder.Configuration.GetConnectionString("IdsSQliteConnection")));builder.Services.AddDatabaseDeveloperPageExceptionFilter();//附加自定义用户声明到用户主体
builder.Services.AddScoped<ApplicationUserClaimsPrincipalFactory>();builder.Services.AddDefaultIdentity<ApplicationUser>(o =>
{   // Password settings.o.Password.RequireDigit = false;o.Password.RequireLowercase = false;o.Password.RequireNonAlphanumeric = false;o.Password.RequireUppercase = false;o.Password.RequiredLength = 1;o.Password.RequiredUniqueChars = 1;
}).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddClaimsPrincipalFactory<ApplicationUserClaimsPrincipalFactory>();builder.Services.AddIdentityServer(options =>
{options.LicenseKey = builder.Configuration["IdentityServerLicenseKey"];options.Events.RaiseErrorEvents = true;options.Events.RaiseInformationEvents = true;options.Events.RaiseFailureEvents = true;options.Events.RaiseSuccessEvents = true;
}).AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>{options.IdentityResources["openid"].UserClaims.Add("roleVIP");// Client localhostvar url2 = "localhost";var spaClient2 = ClientBuilder.SPA("BlazorWasmIdentity.Localhost").WithRedirectUri($"https://{url2}:5001/authentication/login-callback").WithLogoutRedirectUri($"https://{url2}:5001/authentication/logout-callback").WithScopes("openid Profile").Build();spaClient2.AllowOfflineAccess = true;spaClient2.AllowedCorsOrigins = new[]{$"https://{url2}:5001"};options.Clients.Add(spaClient2);//2024-1-23 更新测试端点配置项var spaClientBlazor5002 = ClientBuilder.SPA("Blazor5002").WithScopes("api").Build();spaClientBlazor5002.AllowedCorsOrigins = new[]{$"http://0.0.0.0",$"http://0.0.0.0:5001",$"http://0.0.0.0:5002",$"http://localhost",$"http://localhost:5001",$"http://localhost:5002",$"https://localhost",$"https://localhost:5001",$"https://localhost:5002"};foreach (var item in spaClientBlazor5002.AllowedCorsOrigins){spaClientBlazor5002.RedirectUris.Add($"{item}/authentication/login-callback");spaClientBlazor5002.PostLogoutRedirectUris.Add($"{item}/authentication/logout-callback");}spaClientBlazor5002.AllowOfflineAccess = true;options.Clients.Add(spaClientBlazor5002);});builder.Services.AddAuthentication();var autbuilder = new AuthenticationBuilder(builder.Services);
autbuilder.AddGoogle(o =>
{o.ClientId = builder.Configuration["Authentication:Google:ClientId"] ?? "";o.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"] ?? "";o.ClaimActions.MapJsonKey("urn:google:profile", "link");o.ClaimActions.MapJsonKey("urn:google:image", "picture");
});
//autbuilder.AddFacebook(o =>
//{
//    o.AppId = builder.Configuration["Authentication:Facebook:AppId"] ?? "";
//    o.AppSecret = builder.Configuration["Authentication:Facebook:AppSecret"] ?? "";
//});
//autbuilder.AddTwitter(o =>
//{
//    o.ConsumerKey = builder.Configuration["Authentication:Twitter:ConsumerAPIKey"] ?? "";
//    o.ConsumerSecret = builder.Configuration["Authentication:Twitter:ConsumerSecret"] ?? "";
//    o.RetrieveUserDetails = true;
//});
autbuilder.AddGitHub(o =>
{o.ClientId = builder.Configuration["Authentication:Github:ClientID"] ?? "";o.ClientSecret = builder.Configuration["Authentication:Github:ClientSecret"] ?? "";
});
//autbuilder.AddMicrosoftAccount(o =>
//{
//    o.ClientId = builder.Configuration["Authentication:Microsoft:ClientId"] ?? "";
//    o.ClientSecret = builder.Configuration["Authentication:Microsoft:ClientSecret"] ?? "";
//});
//if (WeChat) autbuilder.AddWeChat(o =>
//{
//    o.AppId = Configuration["Authentication:WeChat:AppId"];
//    o.AppSecret = Configuration["Authentication:WeChat:AppSecret"];
//    o.UseCachedStateDataFormat = true;
//})
//autbuilder.AddQQ(o =>
//{
//    o.AppId = builder.Configuration["Authentication:QQ:AppId"] ?? "";
//    o.AppKey = builder.Configuration["Authentication:QQ:AppKey"] ?? "";
//});
autbuilder.AddOpenIdConnect("oidc", "Demo IdentityServer", options =>
{options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;options.SignOutScheme = IdentityServerConstants.SignoutScheme;options.SaveTokens = true;options.Authority = "https://demo.duendesoftware.com";options.ClientId = "interactive.confidential";options.ClientSecret = "secret";options.ResponseType = "code";options.TokenValidationParameters = new TokenValidationParameters{NameClaimType = "name",RoleClaimType = "role"};
});builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseMigrationsEndPoint();app.UseWebAssemblyDebugging();
}
else
{app.UseExceptionHandler("/Error");// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.app.UseHsts();
}app.UseHttpsRedirection();app.UseBlazorFrameworkFiles();
app.UseStaticFiles();app.UseRouting();
app.UseCors(o => o.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());app.UseIdentityServer();
app.UseAuthorization();app.MapBlazorHub();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");app.Run();

6. 运行工程

因为篇幅的关系,具体数据库改为sqlite生成脚本步骤参考以前文章或者直接拉源码测试

  • 点击注册按钮
  • 用户名 test@test.com
  • 密码 1qaz2wsx

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  • 点击 Apply Migrations 按钮

  • 刷新页面

  • 已经可以成功登录

这篇关于Blazor SSR/WASM IDS/OIDC 单点登录授权实例1-建立和配置IDS身份验证服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/697228

相关文章

MySQL zip安装包配置教程

《MySQLzip安装包配置教程》这篇文章详细介绍了如何使用zip安装包在Windows11上安装MySQL8.0,包括下载、解压、配置环境变量、初始化数据库、安装服务以及更改密码等步骤,感兴趣的朋... 目录mysql zip安装包配置教程1、下载zip安装包:2、安装2.1 解压zip包到安装目录2.2

MobaXterm远程登录工具功能与应用小结

《MobaXterm远程登录工具功能与应用小结》MobaXterm是一款功能强大的远程终端软件,主要支持SSH登录,拥有多种远程协议,实现跨平台访问,它包括多会话管理、本地命令行执行、图形化界面集成和... 目录1. 远程终端软件概述1.1 远程终端软件的定义与用途1.2 远程终端软件的关键特性2. 支持的

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

MySQL 中的服务器配置和状态详解(MySQL Server Configuration and Status)

《MySQL中的服务器配置和状态详解(MySQLServerConfigurationandStatus)》MySQL服务器配置和状态设置包括服务器选项、系统变量和状态变量三个方面,可以通过... 目录mysql 之服务器配置和状态1 MySQL 架构和性能优化1.1 服务器配置和状态1.1.1 服务器选项

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2

TP-Link PDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务

《TP-LinkPDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务》近期,路由器制造巨头普联(TP-Link)在用户群体中引发了一系列重要变动,上个月,公司发出了一则通知,明确要求所... 路由器厂商普联(TP-Link)上个月发布公告要求所有用户必须完成实名认证后才能继续使用普联提供的 D

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

Spring Boot整合log4j2日志配置的详细教程

《SpringBoot整合log4j2日志配置的详细教程》:本文主要介绍SpringBoot项目中整合Log4j2日志框架的步骤和配置,包括常用日志框架的比较、配置参数介绍、Log4j2配置详解... 目录前言一、常用日志框架二、配置参数介绍1. 日志级别2. 输出形式3. 日志格式3.1 PatternL

配置springboot项目动静分离打包分离lib方式

《配置springboot项目动静分离打包分离lib方式》本文介绍了如何将SpringBoot工程中的静态资源和配置文件分离出来,以减少jar包大小,方便修改配置文件,通过在jar包同级目录创建co... 目录前言1、分离配置文件原理2、pom文件配置3、使用package命令打包4、总结前言默认情况下,