日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core分布式项目实战(oauth2 + oidc 实现 server部分)--学习笔记

發布時間:2023/12/4 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core分布式项目实战(oauth2 + oidc 实现 server部分)--学习笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

任務15:oauth2 + oidc 實現 server部分

基于之前快速入門的項目(MvcCookieAuthSample):

ASP.NET Core快速入門(第5章:認證與授權)--學習筆記

ASP.NET Core快速入門(第6章:ASP.NET Core MVC)--學習筆記

mvcCookieAuthSample2下載地址:
http://video.jessetalk.cn/course/5/material/217/download

把這個 MVC 注冊登錄的網站變成一個單點登錄,現在它是自己登錄自己使用,我們需要把它的登錄信息返回給第三方

添加 identityserver4 引用

在 startup 中

using IdentityServer4;

按照之前的文章添加 Config.cs

using System.Collections; using System.Collections.Generic; using IdentityServer4.Models; using IdentityServer4.Test;namespace mvcCookieAuthSample {public class Config{public static IEnumerable<Client> GetClients(){return new List<Client>{new Client(){ClientId = "client",AllowedGrantTypes = GrantTypes.Implicit,// 隱式模式ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes = {"api"},}};}public static IEnumerable<ApiResource> GetApiResource(){return new List<ApiResource>{new ApiResource("api", "My Api")};}public static IEnumerable<IdentityResource> GetIdentityResources(){return new List<IdentityResource>{new IdentityResources.OpenId(),new IdentityResources.Profile(),new IdentityResources.Email(),};}public static List<TestUser> GetTestUsers(){return new List<TestUser>{new TestUser{SubjectId = "1",Username = "mingsonzheng",Password = "123456"}};}} }

startup 的 ConfigureServices

// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) {services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryClients(Config.GetClients()).AddInMemoryApiResources(Config.GetApiResource()).AddInMemoryIdentityResources(Config.GetIdentityResources()).AddTestUsers(Config.GetTestUsers());//services.AddDbContext<ApplicationDbContext>(options =>//{// options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));//});//services.AddIdentity<ApplicationUser, ApplicationUserRole>()// .AddEntityFrameworkStores<ApplicationDbContext>()// .AddDefaultTokenProviders();//services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)// .AddCookie(options => {// options.LoginPath = "/Account/Login";// });//services.Configure<IdentityOptions>(options =>//{// options.Password.RequireLowercase = true;// options.Password.RequireNonAlphanumeric = true;// options.Password.RequireUppercase = true;// options.Password.RequiredLength = 12;//});services.AddMvc(); }

startup 的 Configure 中 UseIdentityServer

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();//app.UseAuthentication();app.UseIdentityServer();app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");}); }

我們已經把 IdentityServer4 添加到 MVC 程序中,接著需要在 Controller 中實現這個邏輯

首先注釋 AccountController 原先的登錄邏輯

//private UserManager<ApplicationUser> _userManager; //private SignInManager<ApplicationUser> _signInManager;

Logout 中使用 HttpContext.SignOutAsync 替換

public async Task<IActionResult> Logout() {//await _signInManager.SignOutAsync();await HttpContext.SignOutAsync();return RedirectToAction("Index", "Home"); }

接著改造登錄的邏輯,我們需要驗證用戶名和密碼,前面我們在 Config 中添加了 TestUser,它被放在 TestUserStore 中,可以通過依賴注入引用進來,有了它之后就可以在登錄的時候拿到用戶名和密碼

private readonly TestUserStore _users;public AccountController(TestUserStore users) {_users = users; }

因為 TestUser 本身不提供 Email 登錄,所以我們需要修改 LoginViewModel 以及 Login.cshtml

LoginViewModel

[Required] //[DataType(DataType.EmailAddress)] //public string Email { get; set; } public string UserName { get; set; }

Login.cshtml

<div class="form-group"><label asp-for="UserName"></label><input asp-for="UserName" class="form-control" /><span asp-validation-for="UserName" class="text-danger"></span> </div>

改造登錄的邏輯

public async Task<IActionResult> Login(LoginViewModel loginViewModel,string returnUrl) {if (ModelState.IsValid){//ViewData["ReturnUrl"] = returnUrl;//var user = await _userManager.FindByEmailAsync(loginViewModel.Email);//if (user == null)//{// ModelState.AddModelError(nameof(loginViewModel.Email), "Email not exists");//}//else//{// await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = true });// return RedirectToLoacl(returnUrl);//}ViewData["ReturnUrl"] = returnUrl;var user = _users.FindByUsername(loginViewModel.UserName);if (user == null){ModelState.AddModelError(nameof(loginViewModel.UserName), "UserName not exists");}else{if (_users.ValidateCredentials(loginViewModel.UserName, loginViewModel.Password)){var props = new AuthenticationProperties{IsPersistent = true,ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30)),};await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(HttpContext,user.SubjectId,user.Username,props);return RedirectToLoacl(returnUrl);}ModelState.AddModelError(nameof(loginViewModel.Password), "Wrong Password");}}return View(); }

這樣,我們就實現了一個通過 IdentityServer4 下的方法來實現了一個登錄邏輯,然后做了一個跳轉,下一節再把客戶端加進來

課程鏈接

http://video.jessetalk.cn/course/explore

相關文章

ASP.NET Core分布式項目實戰(oauth2與open id connect 對比)--學習筆記

ASP.NET Core分布式項目實戰(詳解oauth2授權碼流程)--學習筆記

ASP.NET Core分布式項目實戰(oauth密碼模式identity server4實現)--學習筆記

ASP.NET&nbsp;Core分布式項目實戰(第三方ClientCredential模式調用)--學習筆記

ASP.NET Core分布式項目實戰(客戶端集成IdentityServer)--學習筆記

ASP.NET Core分布式項目實戰(業務介紹,架構設計,oAuth2,IdentityServer4)--學習筆記

ASP.NET Core分布式項目實戰(課程介紹,MVP,瀑布與敏捷)--學習筆記

ASP.NET Core快速入門 -- 學習筆記匯總


創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的ASP.NET Core分布式项目实战(oauth2 + oidc 实现 server部分)--学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。