博客
关于我
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.cs 的 ConfigureServices 方法中,添加以下内容:

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.cs 的 Configure 方法中,添加以下内容:

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/

你可能感兴趣的文章
Python 学习日记第三篇 -- 字典
查看>>
Python 学习笔记(一)Data type
查看>>
python 安装echarts
查看>>
python 安装opencv及问题解决
查看>>
Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
查看>>
Python 安装避坑指南:从入门到进阶
查看>>
Python 安装配置详解
查看>>
python 实现儿童算术游戏
查看>>
python 实现字符串转整型
查看>>
Python 实现定时任务的八种方案!
查看>>
Python 实现自动化测试 dubbo 协议接口
查看>>
python 对json数据读取及保存与读取,对dump,dumps,load,loads的理解
查看>>
Python 对mysql数据库的操作
查看>>
Python 对象数据库列表
查看>>
Python 导入requests报错No module named requests
查看>>
python 将函数加到列表中进行调用
查看>>
python 将图片与字符串相互转换
查看>>
Python 嵌套字典全面指南
查看>>
Python 工具v简介
查看>>
python 常见内置函数setattr、getattr、delattr、setitem、getitem、delitem
查看>>