IdentityServer4[5]简化模式
Implicit简化模式(直接通过浏览器的链接跳转申请令牌)

简化模式是相对于授权码模式而言的。其不再需要【Client】的参与,所有的认证和授权都是通过浏览器来完成的。
创建项目
IdentityServer的ASP.NET Core Web空项目,端口5300
MvcClient的ASP.NET Core Web项目,端口5301

IdentityServer准备工作
定义API资源
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>()
{
new ApiResource("api","My Api")
};
}
public static IEnumerable<IdentityResource> GetIdentityResource()
{
return new List<IdentityResource>()
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email()
};
}
定义客户端
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId="mvc",
AllowedGrantTypes = GrantTypes.Implicit,
ClientSecrets = new List<Secret>()
{
new Secret("secret".Sha256())
},
RequireConsent = false,
RedirectUris = {"http://localhost:5301/signin-oidc"},
PostLogoutRedirectUris = {"http://localhost:5301/signout-callback-oidc"},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OpenId
}
}
};
}
定义测试用户
public static List<TestUser> GetUsers()
{
return new List<TestUser>()
{
new TestUser()
{
SubjectId = "1",
Username = "Test1",
Password = "123456"
}
};
}
配置IdentityServer
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryClients(Config.GetClients())
.AddInMemoryApiResources(Config.GetResources())
.AddInMemoryIdentityResources(Config.GetIdentityResource())
.AddTestUsers(Config.GetUsers());
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
MvcClient准备
在Home控制器上,增加[Authorize]特性(授权)
[Authorize]
public class HomeController : Controller
Startup增加如下代码:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryClients(Config.GetClients())
.AddInMemoryApiResources(Config.GetResources())
.AddInMemoryIdentityResources(Config.GetIdentityResource())
.AddTestUsers(Config.GetUsers());
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
IdentityServer中Account控制器
public class AccountController : Controller
{
private readonly TestUserStore _users;
public AccountController(TestUserStore users)
{
_users = users;
}
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel, string returnUrl = null)
{
if (ModelState.IsValid)
{
ViewData["ReturnUrl"] = returnUrl;
var user = _users.FindByUsername(loginViewModel.UserName);
if (user == null)
{
ModelState.AddModelError(nameof(loginViewModel.UserName), "UserName not exists");
}
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 Redirect(returnUrl);
}
else
{
ModelState.AddModelError(nameof(loginViewModel.Password), "password wrong");
}
}
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index", "Home");
}
}
定义Model
public class LoginViewModel
{
[Required]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
前端代码
@model LoginViewModel
@{
ViewData["Title"] = "Login";
}
<h2>Login</h2>
<div class="row">
<div class="col-md-4">
<section>
<form method="post" asp-controller="Account" asp-action="Login" asp-route-returnUrl="@ViewData["ReturnUrl"]">
<h4>Use a local account to log in.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<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>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log in</button>
</div>
</form>
</section>
</div>
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
先启动IdentityServer(5300),然后启动MvcClient(5301),会直接跳转到IdentityServer的登陆页,登陆后,会返回MvcClient的Home页。
IdentityServer4[5]简化模式的更多相关文章
- IdentityServer4系列 | 简化模式
一.前言 从上一篇关于资源密码凭证模式中,通过使用client_id和client_secret以及用户名密码通过应用Client(客户端)直接获取,从而请求获取受保护的资源,但是这种方式存在clie ...
- Core篇——初探IdentityServer4(OpenID Connect模式)
Core篇——初探IdentityServer4(OpenID Connect客户端验证) 目录 1.Oauth2协议授权码模式介绍2.IdentityServer4的OpenID Connect客户 ...
- 认证授权:IdentityServer4 - 各种授权模式应用
前言: 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例 授权模式: 环境准备 a)调整项目结构如下: b)调整cz.Id ...
- asp.net权限认证:OWIN实现OAuth 2.0 之简化模式(Implicit)
asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...
- 接口测试工具-Jmeter使用笔记(八:模拟OAuth2.0协议简化模式的请求)
背景 博主的主要工作是测试API,目前已经用Jmeter+Jenkins实现了项目中的接口自动化测试流程.但是马上要接手的项目,API应用的是OAuth2.0协议授权,并且采用的是简化模式(impli ...
- Core篇——初探IdentityServer4(客户端模式,密码模式)
Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...
- IdentityServer4 自定义授权模式
IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode.ClientCredentials.Password.RefreshToken.DeviceCode), ...
- asp.net core 使用identityServer4的密码模式来进行身份认证(一)
IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后 ...
- IdentityServer4(客户端授权模式)
1.新建三个项目 IdentityServer:端口5000 IdentityAPI:端口5001 IdentityClient: 2.在IdentityServer项目中添加IdentityServ ...
随机推荐
- js判断checkbox是否选中 .checked不管用
今天开发遇到一个小问题,记小本本记小本本 document.getElementById("id").checked //正确 //如果返回值为true代表选中 //如果返回值为f ...
- flink双流join
package com.streamingjoin import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor ...
- 2020年秋游戏开发-Gluttonous Snake
此作业要求参考https://edu.cnblogs.com/campus/nenu/2020Fall/homework/11577 GitHub地址为https://github.com/15011 ...
- Spring系列之集成Druid连接池及监控配置
前言 前一篇文章我们熟悉了HikariCP连接池,也了解到它的性能很高,今天我们讲一下另一款比较受欢迎的连接池:Druid,这是阿里开源的一款数据库连接池,它官网上声称:为监控而生!他可以实现页面监控 ...
- MySQL-SQL基础-查询1
#子查询-某些情况下,当进行查询的时候,需要的条件是另外一个select语句的结果,这个时候就要用到子查询.用于子查询的关键字主要包括: in.not in.=.!=.exists.not exist ...
- netty系列之:搭建自己的下载文件服务器
目录 简介 文件的content-type 客户端缓存文件 其他HTTP中常用的处理 文件内容展示处理 文件传输进度 总结 简介 上一篇文章我们学习了如何在netty中搭建一个HTTP服务器,讨论了如 ...
- APMserv 5.2.6 安装教程
1.下载APMServ5.2.6.rar压缩包后解压,得到文件APMServ5.1.2.exe,其余两个没什么大用,APMServ解压缩说明.txt可以看一下,里面详细介绍了APMServ的功能和注意 ...
- Linux centos7 nginx 的安装
2021-08-18 1. 环境 # 操作系统[root@test007 /]# uname -aLinux test007 3.10.0-862.el7.x86_64 #1 SMP Fri Apr ...
- cmd编译java时常见错误
中文乱码 在执行javac时出现如图所示问题, 解决方法: 改用 javac -encoding UTF-8执行 找到路径:控制面板--系统和安全--系统--高级系统设置--环境变量--系统变量. 新 ...
- Java学习笔记--常用容器
容器 1. 出现原因 解决程序运行时需要创建新对象,在程序运行前不知道运行的所需的对象数量甚至是类型的问题. Java中提供了一套集合类来解决这些问题包括:List.Set.Queue.Map 2. ...