本文共 4552 字,大约阅读时间需要 15 分钟。
基于之前的快速入门项目(MvcCookieAuthSample),我们需要将现有的注册登录网站转换为单点登录(SSO),并将登录信息返回给第三方。接下来,我们将详细介绍如何实现这一目标。
首先,我们需要在项目中添加 IdentityServer4 的引用,并在启动配置文件中进行相关配置。
在 Startup.cs 的开头部分添加以下行:
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 GetClients() { return new List { new Client { ClientId = "client", AllowedGrantTypes = GrantTypes.Implicit, ClientSecrets = new[] { new Secret("secret".Sha256()) }, AllowedScopes = { "api" } } }; } public static IEnumerable GetApiResources() { return new List { new ApiResource("api", "My Api") }; } public static IEnumerable GetIdentityResources() { return new List { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email() }; } public static List GetTestUsers() { return new List { new TestUser { SubjectId = "1", Username = "mingsonzheng", Password = "123456" } }; } } } 在 Startup.cs 的 ConfigureServices 方法中,添加以下内容:
public void ConfigureServices(IServiceCollection services){ services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryClients(Config.GetClients()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddTestUsers(Config.GetTestUsers()); // 以下代码保留不变,用于身份验证 services.AddMvc();} 在 Startup.cs 的 Configure 方法中,添加以下内容:
app.UseIdentityServer();
在 AccountController 中,注释掉原有的登录逻辑:
// private UserManager_userManager;// private SignInManager _signInManager;// public async Task 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 RedirectToAction("Index", "Home");// }// }// return View();// }
在 AccountController 中,注入 TestUserStore:
private readonly TestUserStore _users;public AccountController(TestUserStore users){ _users = users;} 然后,修改登录方法:
public async TaskLogin(LoginViewModel loginViewModel, string returnUrl){ if (!ModelState.IsValid) { return View(); } 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 HttpContext.SignInAsync( user.SubjectId, user.Username, props ); return Redirect(returnUrl); } else { ModelState.AddModelError(nameof(loginViewModel.Password), "Wrong Password"); } } return View();}
在 LoginViewModel 中,添加以下属性:
[Required][DataType(DataType.EmailAddress)]public string Email { get; set; }public string UserName { get; set; } 在 Login.cshtml 中,修改表单字段:
通过以上步骤,我们已经将原有的登录逻辑替换为基于 IdentityServer4 的单点登录实现。接下来的任务是添加客户端,完成 OAuth2 + OIDC 的完整实现。
如果有任何问题或需要进一步的帮助,请随时与我联系(MingsonZheng@outlook.com)。
转载地址:http://rpkkz.baihongyu.com/