任务15:oauth2 + oidc 实现 server部分

基于之前快速入门的项目(MvcCookieAuthSample):

https://www.cnblogs.com/MingsonZheng/p/11614686.html

https://www.cnblogs.com/MingsonZheng/p/11623815.html

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

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

ASP.NET Core分布式项目实战(oauth2 + oidc 实现 server部分)--学习笔记的更多相关文章

  1. ASP.NET Core分布式项目实战

    ASP.NET Core开发者成长路线图 asp.net core 官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/getting-started/ ...

  2. 【笔记目录1】ASP.NET Core分布式项目实战

    当前标签: ASP.NET Core分布式项目实战 共2页: 1 2 下一页  35.Docker安装Mysql挂载Host Volume GASA 2019-06-20 22:02 阅读:51 评论 ...

  3. 【笔记目录2】ASP.NET Core分布式项目实战

    当前标签: ASP.NET Core分布式项目实战 共2页: 上一页 1 2  11.ClientCredential模式总结 GASA 2019-03-11 12:59 阅读:26 评论:0 10. ...

  4. 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理(内容可能会有部分,推荐看源视频学习) 前言 由于之前的博客都是基于其他的博客进行开发,现在重新整理一下方便 ...

  5. ASP.NET Core分布式项目实战-目录

    前言 今年是2018年,发现已经有4年没有写博客了,在这4年的时光里,接触了很多的.NET技术,自己的技术也得到很大的进步.在这段时光里面很感谢张队长以及其他开发者一直对.NET Core开源社区做出 ...

  6. 【ASP.NET Core分布式项目实战】(二)oauth2 + oidc 实现 server部分

    本博客根据http://video.jessetalk.cn/my/course/5视频整理(内容可能会有部分,推荐看源视频学习) 资料 我们基于之前的MvcCookieAuthSample来做开发 ...

  7. 【ASP.NET Core分布式项目实战】(一)IdentityServer4登录中心、oauth密码模式identity server4实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理 资料 OAuth2 流程:http://www.ruanyifeng.com/blog/2014/05/o ...

  8. 【ASP.NET Core分布式项目实战】(五)Docker制作dotnet core控制台程序镜像

    Docker制作dotnet core控制台程序镜像 基于dotnet SDK 新建控制台程序 mkdir /home/console cd /home/console dotnet new cons ...

  9. 【ASP.NET Core分布式项目实战】(六)Gitlab安装

    Gitlab GitLab是由GitLabInc.开发,使用MIT许可证的基于网络的Git仓库管理工具,且具有wiki和issue跟踪功能.使用Git作为代码管理工具,并在此基础上搭建起来的web服务 ...

  10. ASP.NET Core分布式项目-3.oauth2与open id connect 对比

    oauth2 open id connect

随机推荐

  1. Go-用本地时间解析时间字符串

    Go-用本地时间解析时间字符串 1. 指定本地时区 const ( gLocalTimeZone = "Asia/Shanghai" ) 2. 加载本地时区 var ( gLoca ...

  2. OpenGauss 单机版安装

    OpenGauss 单机版安装 银河麒麟的前置事项 yum -y install libaio-devel flex bison ncurses-devel glibc-devel patch rea ...

  3. [转帖]TiDB 数据库统计表的大小方法

    简介:TiDB统计表的大小,列出了一些方法: 1.第一种的统计方式: 基于统计表 METRICS_SCHEMA.store_size_amplification 要预估 TiDB 中一张表的大小,你可 ...

  4. [转帖]七. PostgreSQL逻辑结构(1)—数据库和模式

    https://www.jianshu.com/p/ee8b1bdfdb19 在PostgreSQL里,逻辑结构从高到底依次是:数据库.模式(又叫架构).表.行.当我们打开PostgreSQL官方自带 ...

  5. [转帖]关系模型到 Key-Value 模型的映射

    https://cn.pingcap.com/blog/tidb-internal-2 在这我们将关系模型简单理解为 Table 和 SQL 语句,那么问题变为如何在 KV 结构上保存 Table 以 ...

  6. SQLServer 隔离级别的简单学习

    SQLServer 隔离级别的简单学习 背景 上周北京一个项目出现了卡顿的现象. 周末开发测试加紧制作测试发布了补丁,但是并没有好转. 上周四时跟研发訾总简单沟通过, 怀疑是隔离级别有关系.但是不敢确 ...

  7. killall 以及 pkill 等命令

    https://zhidao.baidu.com/question/1500084252693125099.html // 通过 killall 命令killall nginx// 通过 pkill ...

  8. 除了Adobe之外,还有什么方法可以将Excel转为PDF?

    前言 Java是一种广泛使用的编程语言,它在企业级应用开发中发挥着重要作用.而在实际的开发过程中,我们常常需要处理各种数据格式转换的需求.今天小编为大家介绍下如何使用葡萄城公司的的Java API 组 ...

  9. Spring Cloud 系列:基于Seata 实现 XA模式

    https://seata.io/zh-cn/docs/user/mode/xa https://seata.io/zh-cn/docs/dev/mode/xa-mode XA 规范 是 X/Open ...

  10. React中css的module

    处理css全局作用 现在有这样一个场景: A页面和B页面都有一个相同的类名 我们在A页面中有引入css. B页面没有css 在我们切换A和B页面的时候. A页面的css也作用在了B页面. 我们只希望A ...