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. [转]C# 互操作性入门系列(一):C#中互操作性介绍

    传送门 C#互操作系列文章: C# 互操作性入门系列(一):C#中互操作性介绍 C# 互操作性入门系列(二):使用平台调用调用Win32 函数 C# 互操作性入门系列(三):平台调用中的数据封送处理 ...

  2. centos7 添加磁盘到/(根目录下),扩展VG卷和lv

    转载自:http://blog.itpub.net/25469263/viewspace-2662215/ centos7中使用vg方式扩充root分区 1.创建pv fdisk /dev/sdb 输 ...

  3. unity优化 — 纹理(优化)通道分离

    unity针对Android平台还提供了通道分离的方式:将图片(sprite)压缩成ETC1,提取Alpha生成一张通道图.unity将通道图保存的格式为a8格式,目的为了让混合起来的Alpha效果很 ...

  4. spring AOP事务

    1 <bean id="tttt" class="com.ry.project.dataSouces.UserLogger"/> 2 <aop ...

  5. 你知道 ES6~ES12等叫法是怎么来的吗?

    你知道 ES6~ES12等叫法是怎么来的吗? 前言 作为一名前端开发,学习 JavaScript 自是天经地义的事,但是,JavaScript 的发展历史是怎样的,恐怕有相当一部分人都不太了解. 我们 ...

  6. 一键备份公众号的所有文章到PDF,再也不用担心想看的文章被删了

    有的时候,我们会发现收藏的某个微信公众号文章会被删或者和谐了,尤其是对自己非常实用的文章,一定会后悔当初怎么没有复制或者备份下来. 单篇的公众号文章要备份,随便百度一下就能找到非常多方法,这里就不多废 ...

  7. Qt5完美解决 界面显示中文乱码

    最近在学习Qt,可是一直头疼于中文乱码问题,上网搜了一下,很多都是Qt4中使用如下方法: QTextCodec *codec = QTextCodec::codecForName("gbk& ...

  8. 关于Quartus构建nios软核以及eclipse建立c语言工程以及成功下载到FPGA芯片过程遇到的各种问题以及解决方法详解

    这不是一篇构建nios的教程,而是遇到的各种问题以及解决方法.至于构建教程,网上一大把,我推荐正点原子的FPGA教程,比较新,比较详细,通俗易懂!!! 这里以一个点亮LED灯的Nios软核为例,很明显 ...

  9. MPI集群搭建

    高性能计算     ubantu下集群搭建 参考博客:https://blog.csdn.net/u012304016/article/details/52423738(尊重别人的知识产权),一些细节 ...

  10. 15-SpringCloud Stream

    Stream是什么及Binder介绍 官方文档1 官方文档2 Cloud Stream中文指导手册 什么是Spring Cloud Stream? 官方定义Spring Cloud Stream是一个 ...