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快速入门 -- 学习笔记汇总


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/310040.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[C++STL]set容器用法介绍

代码如下: #include <iostream> #include <set> using namespace std;void printSet(set<int>&s) {for (set<int>::iterator it s.begin(); it ! s.end(); it){cout << *it << " ";}cout << endl; }void test01() {…

Equations HDU - 1496(哈希或三层for循环)求满足公式有多少种情况

题意:求x在(-100<x<100)区间上&#xff0c;已知a,b,c,d&#xff0c;满足a*x1^2b*x2^2c*x3^2d*x4^20 的情况有多少种 思路&#xff1a;很明显四层for循环肯定超时&#xff0c;可用三层for循环来判断&#xff0c;或是&#xff0c;两两组合&#xff0c;求多少种情况。分正负…

java.time.format例子_java格式化时间示例

实现日期的格式化&#xff0c;需要用到类: java.text.DateFormatDateFormat没有可以直接使用的构造函数&#xff0c;一般使用DateFormate的子类---java.text.SimpleDateFormat完成构造.public SimpleDateFormat(String pattern)测试代码import java.text.DateFormat;import jav…

[C++STL]map容器用法介绍

代码如下: #include <iostream> #include <string> #include <map> using namespace std;void printMap(map<int,int>&m) {for (map<int, int>::iterator it m.begin(); it ! m.end(); it){cout << "key " << it-&…

ABP框架 v2.7.0已经发布!

ABP框架和ABP商业版 v2.7已经发布.我们没有为2.4,2.5和2.6发布博客文章,所以这篇文章也将涵盖这几个版本中新增内容和过去的2个月里我们完成了什么.关于发布周期与开发之前说过我们已经开始每两个星期发布一个新的次要功能版本,一般在星期四.我们的目标是尽快提供新功能.在过去…

Colossal Fibonacci Numbers! UVA - 11582(斐波那契求模)+快速幂+周期规律

题意&#xff1a; 给出64位整数a、b以及不超过1000的正整数n&#xff0c;求斐波那契数列第a ^ b项模n的结果。 输入&#xff1a;情况数T&#xff0c;之后T行每行a、b、n。 输出&#xff1a;斐波那契数列第a ^ b项模n的结果。 分析&#xff1a;由于斐波那契数列的每一项都是由…

java中factory方法_Java的23中设计模式--工厂方法模式(Factory Method)

1.普通工厂模式工厂类/*** Title Factory.java* Package factory.factory1* date 2015-1-22 上午10:16:02*versionV1.0*/packagefactory.factory1;/*** ClassName Factory* date 2015-1-22 上午10:16:02*/public classFactory {publicSender procedure(String type) {if("…

GCD and LCM HDU - 4497(素数打表+唯一分解定理)求多少种情况

题目大意&#xff1a; 给你两个数最小公倍数L,最大公约数G&#xff0c;问你有多少有序数组&#xff08;x,y,z)满足GCD&#xff08;x,y,z)G,LCM(x,y,z)L,首先如果gcd(x,y,z)G, 思路分析&#xff1a; 当这样的组合存在的时候&#xff0c;求gcd&#xff08;x,y,z&#xff09;1且l…

[C++STL]仿函数用法介绍

代码如下: #include <iostream> #include <string> using namespace std;//函数对象在使用时&#xff0c;可以像普通函数那样调用&#xff0c;可以有参数&#xff0c;可以有返回值 class MyAdd { public:int operator()(int a, int b){return a b;} };void test0…

【壹刊】Azure AD(二)调用受Microsoft 标识平台保护的 ASP.NET Core Web API (上)

—————————Grant_Allen 是一位博客园新晋博主&#xff0c;目前开始专注于Azure方向的学习和研究&#xff0c;是我认识不多的、打算长时间研究Azure的群友&#xff0c;因此打算帮他开个专栏&#xff0c;同时也希望并祝愿他能一直坚持下去&#xff0c;学有所成。正文一&a…

[C++STL]常用遍历算法

代码如下&#xff1a; #include <iostream> #include <algorithm> #include <vector> using namespace std;void print01(int val) {cout << val << " "; }class print02 { public:void operator()(int val){cout << val <&…

用Visual Studio2019自定义项目模板

项目模板简介众所周知&#xff0c;在我们使用VS新建项目时&#xff0c;都需要选择一个项目模板&#xff0c;如下图&#xff1a;我们选择完项目模板进行创建&#xff0c;创建完成之后&#xff0c;可以发现项目中已经包含了一些基础的文件。例如MVC&#xff1a;可以看到&#xff…

A/B HDU - 1576 (逆元或拓展欧几里得或数学公式)多解法求大数结果

题意&#xff1a;求(A/B)%9973&#xff0c;但由于A很大&#xff0c;我们只给出n(nA%9973)(我们给定的A必能被B整除&#xff0c;且gcd(B,9973) 1)。 思维&#xff1a;&#xff08;1&#xff09;逆元扩展欧几里得算法&#xff1a;满足a*k≡1 (mod p)的k值就是a关于p的乘法逆元。…

java线程同步的优缺点_浅谈java多线程编程

一、多线程的优缺点多线程的优点&#xff1a;1)资源利用率更好2)程序设计在某些情况下更简单3)程序响应更快多线程的代价&#xff1a;1)设计更复杂虽然有一些多线程应用程序比单线程的应用程序要简单&#xff0c;但其他的一般都更复杂。在多线程访问共享数据的时候&#xff0c;…

[C++STL]常用排序算法

代码如下: #include <iostream> #include <algorithm> #include <vector> using namespace std;void myPrint(int val) {cout << val << " "; }void test01() {vector<int>v;v.push_back(10);v.push_back(30);v.push_back(50);…

Fliptile POJ - 3279 (翻转)(二进制+对第一行暴力遍历翻转的位置)

题意&#xff1a;给你一个给你一个矩阵&#xff0c;有黑白两个状态。每次你可以选择一个变为其相反的状态&#xff0c;它周围的4个都会变成相反的状态。问你最少需要改变多少个使得矩阵中的状态全为白色&#xff0c;若有多个答案&#xff0c;输出字典序最小的 思路&#xff1a…

新基建火了,开源云计算渠道能做什么?

导语对于开源云计算厂商而言&#xff0c;如果希望在抢滩新基建上构建差异化竞争优势&#xff0c;具备高超的售前技能、售后体验&#xff0c;并拥有创新的技术服务能力与解决方案构建能力是实有必要的。巧了&#xff0c;这些都与渠道构建息息相关。开源云计算厂商在此前的渠道激…

python socket编程之双方相互通信简单实例_Python socket实现的简单通信功能示例

套接字(socket)是计算机网络数据结构&#xff0c;在任何类型的通信开始之前&#xff0c;网络应用程序必须创建套接字&#xff0c;可以将其比作电话的插孔&#xff0c;没有它将无法进行通信常用的地址家族AF_UNIX&#xff1a;基于文件&#xff0c;实现同一主机不同进程之间的通信…

[C++STL]常用拷贝和替换算法

代码如下: #include <iostream> #include <algorithm> #include <vector> #include <ctime> using namespace std;void myPrint(int val) {cout << val << " "; }void test01() {vector<int>v1;for (int i 0; i < 10…

Jin Ge Jin Qu hao UVA - 12563 (劲歌金曲)01背包,求装入的东西最多(相同多时价值大)

题目&#xff1a;白书p274 题意: KTV里面有n首歌曲你可以选择,每首歌曲的时长都给出了. 对于每首歌曲,你最多只能唱1遍. 现在给你一个时间限制t (t<10^9) , 问你在最多t-1秒的时间内可以唱多少首歌曲num , 且最长唱歌时间是多少time (time必须<t-1) ? 最终输出num1 和…