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 按钮

  • 刷新页面

  • 已经可以成功登录

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/461616.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

v-if 和v-for的联合规则及示例

第073个 查看专栏目录: VUE ------ element UI 专栏目标 在vue和element UI联合技术栈的操控下&#xff0c;本专栏提供行之有效的源代码示例和信息点介绍&#xff0c;做到灵活运用。 提供vue2的一些基本操作&#xff1a;安装、引用&#xff0c;模板使用&#xff0c;computed&a…

单片机学习笔记---LED点阵屏显示图形动画

目录 LED点阵屏显示图形 LED点阵屏显示动画 最后补充 上一节我们讲了点阵屏的工作原理&#xff0c;这节开始代码演示&#xff01; 前面我们已经说了74HC595模块也提供了8个LED&#xff0c;当我们不使用点阵屏的时候也可以单独使用74HC595&#xff0c;这8个LED可以用来测试7…

【原创 附源码】Flutter海外登录--Google登录最详细流程

最近接触了几个海外登录的平台&#xff0c;踩了很多坑&#xff0c;也总结了很多东西&#xff0c;决定记录下来给路过的兄弟坐个参考&#xff0c;也留着以后留着回顾。更新时间为2024年2月8日&#xff0c;后续集成方式可能会有变动&#xff0c;所以目前的集成流程仅供参考&#…

PySpark(三)RDD持久化、共享变量、Spark内核制度,Spark Shuffle、Spark执行流程

目录 RDD持久化 RDD 的数据是过程数据 RDD 缓存 RDD CheckPoint 共享变量 广播变量 累加器 Spark 内核调度 DAG DAG 的宽窄依赖和阶段划分 内存迭代计算 Spark是怎么做内存计算的? DAG的作用?Stage阶段划分的作用? Spark为什么比MapReduce快&#xff1f; Spa…

JMM(Java内存模型)

定义 JMM即Java内存模型(Java memory model)&#xff0c;在JSR133里指出了JMM是用来定义一个一致的、跨平台的内存模型&#xff0c;是缓存一致性协议&#xff0c;用来定义数据读写的规则。 内存可见性 在Java中&#xff0c;不同线程拥有各自的私有工作内存&#xff0c;当线程…

(全网最全)微型计算机原理与接口技术第六版课后习题答案-周荷琴,冯焕清-第8章中断和可编程中断控制器8259A-中国科学技术大学出版社

含有“AI:”开头的题目的答案是问chat的&#xff0c;看个乐就行&#xff0c;不一定正确 1。 什么叫中断&#xff1f;中断的主要功能是什么&#xff1f; 答:当CPU正在处某件事情的时候,外部发生的某一事件请求CPU迅速去处理,于是,CPU暂时中止当前工作,转去处理所发生的事件,中…

markdown加载自定义字体

写讲义&#xff0c;如果没有个像样 的字体多少有点难受。 最终的结果是劝退。 一、需要特定的markdown编辑器&#xff0c;我用的vscode 如果使用joplin、gitee的md文件是无法加载、渲染的。 二、 使用vscode想要渲染的话&#xff0c;似乎只能渲染一部分字体文件。下面不多…

Uniapp(uni-app)学习与快速上手教程

Uniapp&#xff08;uni-app&#xff09;学习与快速上手教程 1. 简介 Uniapp是一个跨平台的前端框架&#xff0c;允许您使用Vue.js语法开发小程序、H5、安卓和iOS应用。下面是快速上手的步骤。 2. 创建项目 2.1 可视化界面创建 1、打开 HBuilderX&#xff0c;这是一款专为uni…

【VTKExamples::PolyData】第二十四期 InterpolateTerrain

很高兴在雪易的CSDN遇见你 VTK技术爱好者 QQ:870202403 前言 本文分享VTK样例InterpolateTerrain,希望对各位小伙伴有所帮助! 感谢各位小伙伴的点赞+关注,小易会继续努力分享,一起进步! 你的点赞就是我的动力(^U^)ノ~YO 1. InterpolateTerrain 输出: Interp…

问题:路基施工时以下哪种情况可以不用铺筑试验路段。( ) #经验分享#其他#微信

问题&#xff1a;路基施工时以下哪种情况可以不用铺筑试验路段。&#xff08; &#xff09; A.高速公路和一级公路 B.特殊土质地区公路 C.采用新技术、新材料和新工艺的路基 D.三、四级公路 参考答案如图所示

Java:内部类、枚举、泛型以及常用API --黑马笔记

内部类 内部类是类中的五大成分之一&#xff08;成员变量、方法、构造器、内部类、代码块&#xff09;&#xff0c;如果一个类定义在另一个类的内部&#xff0c;这个类就是内部类。 当一个类的内部&#xff0c;包含一个完整的事物&#xff0c;且这个事物没有必要单独设计时&a…

(1)短距离(<10KM)

文章目录 1.1 Bluetooth 1.2 CUAV PW-Link 1.3 ESP8266 wifi telemetry 1.4 ESP32 wifi telemetry 1.5 FrSky telemetry 1.6 Yaapu双向遥测地面站 1.7 HOTT telemetry 1.8 MSP(MultiWii 串行协议)(4.1 版) 1.9 MSP (version 4.2) 1.10 SiK Radio v1 1.11 SiK Radio …