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 中文文档与实战

IdentityServer4 知多少

jessetalk视频教程

IdentityServer4[5]简化模式的更多相关文章

  1. IdentityServer4系列 | 简化模式

    一.前言 从上一篇关于资源密码凭证模式中,通过使用client_id和client_secret以及用户名密码通过应用Client(客户端)直接获取,从而请求获取受保护的资源,但是这种方式存在clie ...

  2. Core篇——初探IdentityServer4(OpenID Connect模式)

    Core篇——初探IdentityServer4(OpenID Connect客户端验证) 目录 1.Oauth2协议授权码模式介绍2.IdentityServer4的OpenID Connect客户 ...

  3. 认证授权:IdentityServer4 - 各种授权模式应用

    前言: 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例 授权模式: 环境准备 a)调整项目结构如下:   b)调整cz.Id ...

  4. asp.net权限认证:OWIN实现OAuth 2.0 之简化模式(Implicit)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  5. 接口测试工具-Jmeter使用笔记(八:模拟OAuth2.0协议简化模式的请求)

    背景 博主的主要工作是测试API,目前已经用Jmeter+Jenkins实现了项目中的接口自动化测试流程.但是马上要接手的项目,API应用的是OAuth2.0协议授权,并且采用的是简化模式(impli ...

  6. Core篇——初探IdentityServer4(客户端模式,密码模式)

    Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...

  7. IdentityServer4 自定义授权模式

    IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode.ClientCredentials.Password.RefreshToken.DeviceCode), ...

  8. asp.net core 使用identityServer4的密码模式来进行身份认证(一)

    IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后 ...

  9. IdentityServer4(客户端授权模式)

    1.新建三个项目 IdentityServer:端口5000 IdentityAPI:端口5001 IdentityClient: 2.在IdentityServer项目中添加IdentityServ ...

随机推荐

  1. 小白5分钟创建WPF

    创建WPF应用程序 基于生产这里选择.Net Framework进行开发 添加控件 由于不熟悉 高效点 我们这里直接拖拽控件 如果你有一点前端基础 你可以在控件对应Code 根据属性 对控件进行设置 ...

  2. 本文详细阐述如何用C#创建COM组件,并能用VC6.0等调用。

    本文详细阐述如何用C#创建COM组件,并能用VC6.0等调用. 附:本文适用任何VS系列工具. 在用C#创建COM组件时,一定要记住以下几点: 1.所要导出的类必须为公有: 2.所有属性.方法也必须为 ...

  3. PsSetCreateProcessNotifyRoutineEx 创建回调函数

    转载自http://blog.csdn.net/yushiqiang1688/article/details/5209597 最近要做一个进程监控的程序,功能很简单,就是创建和退出进程的时候,能触发我 ...

  4. 翻译Go Blog: 常量

    常量 Pob Pike 2014年8月24日 原文 介绍 Go是一门静态语言,它不允许不同数字类型间的操作.你不能将一个浮点数(float64)和一个整数(int)相加,也不能将一个32位整数(int ...

  5. 前端云原生,以 Kubernetes 为基础设施的高可用 SSR(Vue.js) 渲染微服务初探(开源 Demo)

    背景 笔者在逛掘金的时候,有幸看到掘友狼族小狈开源的 genesis - 一个可以支持 SSR 和 CSR 渲染的微服务解决方案.总体来说思想不错,但是基于 Kubernetes 云原生部署方面一直没 ...

  6. win命令

    netstat -nao | findstr "8888"taskkill /pid 15064 /f清理端口被占用win+r进入cmdcmd窗口中输入notepad进入记事本sh ...

  7. ES6基础之let、const

    es6的块级作用域通俗的讲就是一对花括号中的区域(声明对象的花括号不是块级作用域),块级作用域可以嵌套. let: 1.le声明的变量只在当前(块级)作用域内有效. 2.let声明的变量不能被重复声明 ...

  8. GUI容器之Frame

    Frame public class MyFrame { public static void main(String[] args) { //创建一个Frame对象 Frame frame = ne ...

  9. 微服务架构及raft协议

    微服务架构全景图 服务注册和发现 Client side implement 调用需要维护所有调用服务的地址 有一定的技术难度,需要rpc框架支持 Server side implement 架构简单 ...

  10. Django——实现最基础的评论功能(只有一级评论)

    我对评论功能的理解: --------(1)数据库建一个评论的表 --------(2)前端建一个提交评论的form表单 --------(3)表单提交评论内容后写入到数据库评论表中 -------- ...