<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
IdentityServer4 實現鑑權、授權,AspNetCore Identity實現資料庫使用者管理表直接生成。
ps:IdentityServer4檔案上最後給的例子是 // 設定使用記憶體儲存使用者資訊,但使用 EF 儲存使用者端和資源資訊,
我初步要實現的是 //資料庫儲存使用者資訊 記憶體儲存資源 (下一步資源也放資料庫 以後弄好了有機會更)
一頓參照,包括
防止圖片掛掉打一遍文字:
下面那個是自帶的。
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using MyIDP; using MyIDP.Models; using MyIDP.Permission; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //由此重要 builder.Services.AddDbContext<IdpDbContext>(opt => { opt.UseMySql("server=127.0.0.1;Port=3306;database=AccountDb;uid=root;pwd=123456;", new MySqlServerVersion(new Version(8,0,29))); }); builder.Services.AddIdentity<ApplicationUser, IdentityRole>() .AddUserManager<MyUserManager>() .AddEntityFrameworkStores<IdpDbContext>() .AddDefaultTokenProviders(); builder.Services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(MyIDP.IdpConfig.GetIdentityResources()) .AddInMemoryClients(MyIDP.IdpConfig.GetClients()) .AddInMemoryApiScopes( MyIDP.IdpConfig.GetScope()) .AddInMemoryApiResources( MyIDP.IdpConfig.GetApiResources()) //.AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() //這句可以開啟自主驗證登入使用者 //.AddProfileService<MyProfileService>() .AddAspNetIdentity<ApplicationUser>() //.AddTestUsers(new List<IdentityServer4.Test.TestUser> //{ // new IdentityServer4.Test.TestUser // { // SubjectId="123", // Username = "alice", // Password = "alice", // Claims = new List<Claim>() { // new Claim(JwtClaimTypes.Role, "superadmin"), // new Claim(JwtClaimTypes.Role, "admin") // } // } //}) ; var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseIdentityServer(); app.UseAuthorization(); app.MapControllers(); app.Run();
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using MyIDP; using MyIDP.Models; using MyIDP.Permission; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //由此重要 builder.Services.AddDbContext<IdpDbContext>(opt => { opt.UseMySql("server=127.0.0.1;Port=3306;database=AccountDb;uid=root;pwd=123456;", new MySqlServerVersion(new Version(8,0,29))); }); builder.Services.AddIdentity<ApplicationUser, IdentityRole>() .AddUserManager<MyUserManager>() .AddEntityFrameworkStores<IdpDbContext>() .AddDefaultTokenProviders(); builder.Services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(MyIDP.IdpConfig.GetIdentityResources()) .AddInMemoryClients(MyIDP.IdpConfig.GetClients()) .AddInMemoryApiScopes( MyIDP.IdpConfig.GetScope()) .AddInMemoryApiResources( MyIDP.IdpConfig.GetApiResources()) //.AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() //這句可以開啟自主驗證登入使用者 //.AddProfileService<MyProfileService>() .AddAspNetIdentity<ApplicationUser>() //.AddTestUsers(new List<IdentityServer4.Test.TestUser> //{ // new IdentityServer4.Test.TestUser // { // SubjectId="123", // Username = "alice", // Password = "alice", // Claims = new List<Claim>() { // new Claim(JwtClaimTypes.Role, "superadmin"), // new Claim(JwtClaimTypes.Role, "admin") // } // } //}) ; var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseIdentityServer(); app.UseAuthorization(); app.MapControllers(); app.Run();
因為使用的是記憶體儲存t鑑權資訊的方式,所以建立IdentityServer4的設定類IdpConfig
public static class IdpConfig { public static IEnumerable<IdentityResource> GetIdentityResources() { return new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Address(), new IdentityResources.Phone(), new IdentityResources.Email() }; } public static IEnumerable<ApiResource> GetApiResources() { //return new ApiResource[] //{ // new ApiResource("api1", "My API #1",new List<string>(){JwtClaimTypes.Role}) //}; //新寫法 return new[] { new ApiResource("api1", "My API #1") { Scopes = { "scope1"} } }; } public static IEnumerable<Client> GetClients() { return new[] { #region MyRegion //// client credentials flow client //new Client //{ // ClientId = "console client", // ClientName = "Client Credentials Client", // AllowedGrantTypes = GrantTypes.ClientCredentials, // ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) }, // AllowedScopes = { "api1" } //}, #endregion // wpf client, password grant new Client { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = //允許當存取的資源 { "scope1", //"api1", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Email, IdentityServerConstants.StandardScopes.Address, IdentityServerConstants.StandardScopes.Phone, IdentityServerConstants.StandardScopes.Profile } } }; } public static IEnumerable<ApiScope> GetScope() { return new ApiScope[] { new ApiScope("scope1"), new ApiScope("scope2"), }; } }
資料庫的usernamager
public class MyUserManager : UserManager<ApplicationUser> { public MyUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, optionsAccessor, new MyPasswordHasher(), userValidators, passwordValidators, keyNormalizer, errors, services, logger) { optionsAccessor.Value.Password.RequireDigit = false; optionsAccessor.Value.Password.RequiredLength = 4; optionsAccessor.Value.Password.RequireLowercase = false; optionsAccessor.Value.Password.RequireUppercase = false; optionsAccessor.Value.Password.RequireNonAlphanumeric = false; } }
重寫驗證密碼的方法類MyResourceOwnerPasswordValidator,(如果沒有開啟Program中的AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() 則不需要)
public class MyResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { public readonly SignInManager<ApplicationUser> signInManager; private readonly MyUserManager userManager; //public readonly IEventService service; public MyResourceOwnerPasswordValidator(MyUserManager userService, SignInManager<ApplicationUser> signInManager)//, IEventService service) { userManager = userService; this.signInManager = signInManager; //this.service = service; } public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "驗證被拒絕,使用者名稱或者密碼為空。"); return; } var user = await userManager.FindByNameAsync(context.UserName); if (user == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "驗證失敗,不存在當前使用者。"); return; } //檢驗使用者密碼(雖然我也不知道他的密碼是採用什麼加密方式得到的,但是我也不需要知道) var passwordPass = await userManager.CheckPasswordAsync(user, context.Password); if (!passwordPass) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "驗證失敗,使用者憑證錯誤"); return; } else { try { await userManager.AddLoginAsync(user, new UserLoginInfo(user.Id, "", user.UserName)); } catch (Exception ex) { ; } finally { context.Result = new GrantValidationResult(user.Id, GrantType.ResourceOwnerPassword, new List<Claim>() { new Claim("account", user.UserName) }); } } return; } }
MyPasswordHasher
public class MyPasswordHasher : PasswordHasher<ApplicationUser> { public override string HashPassword(ApplicationUser user, string password) { //PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>(); //var pstr = ph.HashPassword(new ApplicationUser(), password); //return pstr; return password.MD5(); } public override PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword) { if (providedPassword.MD5().Equals(hashedPassword)) { return PasswordVerificationResult.Success; } else { return PasswordVerificationResult.Failed; } } }
建立自己的User類 ApplicationUser繼承 IdentityUser 複寫自帶的AspNetUser表
public class ApplicationUser : IdentityUser { public string MySomething { get; set; } = ""; /// <summary> /// 建立時間 /// </summary> public DateTime CreateTime { get; set; } /// <summary> /// 建立人Id /// </summary> public string CreatorId { get; set; } = ""; /// <summary> /// 否已刪除 /// </summary> public bool Deleted { get; set; } /// <summary> /// 姓名 /// </summary> public string RealName { get; set; } /// <summary> /// 性別 /// </summary> public Sex Sex { get; set; } /// <summary> /// 出生日期 /// </summary> public DateTime? Birthday { get; set; } /// <summary> /// 所屬部門Id /// </summary> public string DepartmentId { get; set; } = ""; public string OtherData { get; set; } = ""; // 使用者角色 使用者許可權 使用者資訊 使用者登入tokens 重新系結與父類別的關係 命名必須和父類別一致 public virtual ICollection<IdentityUserRole<string>> UserRoles { get; set; } public virtual ICollection<IdentityUserClaim<string>> Claims { get; set; } public virtual ICollection<IdentityUserLogin<string>> Logins { get; set; } public virtual ICollection<IdentityUserToken<string>> Tokens { get; set; } } public enum Sex { [Description("男")] Man = 1, [Description("女")] Woman = 0 }
至此可以生成資料庫遷移後 Postman測試一下:
到此這篇關於.Net6整合IdentityServer4 +AspNetCore Identity讀取資料表使用者且鑑權授權管理API的文章就介紹到這了,更多相關.Net6 讀取資料表使用者內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45