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. Vue实现在前端导出Excel 方法1

    也可以去看我的方法2:https://www.cnblogs.com/yingyigongzi/p/10915403.html ------------------------------------ ...

  2. ASP.Net Core Web Api 使用 IdentityServer4 最新版 踩坑记录

    辅助工具 日志追踪包 : Serilog.AspNetCore 源码查看工具 : ILSpy 项目环境 ###: ASP.NetCore 3.1 IdentityServer4 4.0.0+ 主题内容 ...

  3. [转载]getContentPane()

    关于setContentPane()和getContentPane()的应用       我们可以在 JFrame 对象中添加 AWT 或者 Swing 组件.但是,虽然它有 add 方法,却不能直接 ...

  4. reids rdb与aof

    rdb:时合高并发场景,容易备份恢复,会丢失部分数据 1.默认开启的方式,可以进过压缩,可以根据时间点生成快照 2.数据量大的情况下恢复快 3.bgsave一边开启fork保存文件,一边继续响应客户端 ...

  5. ROS catkin_make error Could not find a package configuration file provided by "actionlib_msgs"

    在使用ROS catkin_make编译的时候,出现类似如下错误 CMake Error at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cma ...

  6. Three.js 中 相机的常用参数含义

    Three.js 中相机常用的参数有up.position和lookAt. position是指相机所在的位置,将人头比作相机的话,那么position就是人头的中心的位置: up类似于人的脖子可以调 ...

  7. D3之svg transform 与 css3 transform 区别与联系

    D3就不用多介绍了,在数据可视化界属于大佬级别的js库.在这里主要想记录一下在写程序期间遇到的一个问题. 如下图所示,想完成主视图在小地图上的映射,小地图的白色矩形框用来代表当前主视图可见区域,主视图 ...

  8. Java 学习:对象和类

    对象和类 从认识的角度考虑是先有对象后有类.对象,是具体的事物.类,是抽象的,是对对象的抽象. 从代码运行角度考虑是先有类后又对象.类是对象的模板. 对象:对象是类的一个实例,有状态和行为. 类:类是 ...

  9. 前后端数据交互(四)——fetch 请求详解

    fetch 是 XMLHttpRequest 的升级版,使用js脚本发出网络请求,但是与 XMLHttpRequest 不同的是,fetch 方式使用 Promise,相比 XMLHttpReques ...

  10. 快速模式第二包: quick_inI1_ouR1()

    文章目录 1. 序言 2. quick_inI1_outR1()流程图 3. 快速模式消息②数据包格式 4. 源码分析 4.1 quick_inI1_outR1() 4.2 quick_inI1_ou ...