博客
关于我
ASP.NET Core分布式项目实战(oauth2 + oidc 实现 server部分)--学习笔记
阅读量:409 次
发布时间:2019-03-06

本文共 4453 字,大约阅读时间需要 14 分钟。

任务15:OAuth2 + OIDC 实现 Server 部分

基于之前的快速入门项目(MvcCookieAuthSample),我们需要将现有的注册登录网站转换为单点登录(SSO),并将登录信息返回给第三方。接下来,我们将详细介绍如何实现这一目标。

一、添加 IdentityServer4 引用

首先,我们需要在项目中添加 IdentityServer4 的引用,并在启动配置文件中进行相关配置。

1.1 在 startup.cs 中添加引用

Startup.cs 的开头部分添加以下行:

using IdentityServer4;

1.2 添加配置文件 Config.cs

在项目根目录中创建或修改 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" } }; } }}

1.3 修改 Startup.cs 的 ConfigureServices 方法

Startup.csConfigureServices 方法中,添加以下内容:

public void ConfigureServices(IServiceCollection services){    services.AddIdentityServer()        .AddDeveloperSigningCredential()        .AddInMemoryClients(Config.GetClients())        .AddInMemoryApiResources(Config.GetApiResources())        .AddInMemoryIdentityResources(Config.GetIdentityResources())        .AddTestUsers(Config.GetTestUsers());    // 以下代码保留不变,用于身份验证    services.AddMvc();}

1.4 修改 Startup.cs 的 Configure 方法

Startup.csConfigure 方法中,添加以下内容:

app.UseIdentityServer();

二、注释原有登录逻辑并实现新登录逻辑

2.1 注释原有登录逻辑

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();// }

2.2 实现新登录逻辑

AccountController 中,注入 TestUserStore

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

然后,修改登录方法:

public async Task
Login(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();}

2.3 修改 LoginViewModel 和 Login.cshtml

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/

你可能感兴趣的文章
Oracle中的rownum 和rowid的用法和区别
查看>>
oracle中的大小写、字符、dual、数字、处理、日期、函数、显/隐式、时间、条件表达式case、decode、to_date、to_char、sysdate
查看>>
oracle中表和视图的区别,oracle中常用表和视图
查看>>