前面的部分:

Identity Server 4 从入门到落地(一)—— 从IdentityServer4.Admin开始

Identity Server 4 从入门到落地(二)—— 理解授权码模式

Identity Server 4 从入门到落地(三)—— 创建Web客户端

Identity Server 4 从入门到落地(四)—— 创建Web Api

Identity Server 4 从入门到落地(五)—— 使用Ajax 访问 Web Api

Identity Server 4 从入门到落地(六)—— 简单的单页面客户端

Identity Server 4 从入门到落地(七)—— 控制台客户端

认证服务和管理的github地址: https://github.com/zhenl/IDS4Admin

客户端及web api示例代码的github地址:https://github.com/zhenl/IDS4ClientDemo

在面向企业的信息化项目中,很少有项目是从一张白纸开始,或多或少都要面临与现有项目集成或者遗留项目升级与整合的问题,认证服务的使用更是如此,各种现有系统的单点登录就是认证服务常用的场景之一,因此,如果遗留系统无法使用,那么这个技术在项目中就无法落地使用。现实中仍然存在大量在用的基于.Net Framework的项目,我们需要为这些项目制订与认证服务集成的方案。我们通过创建一个.Net Framework 4.5.2的简单应用来验证方案的可行性,主要使用的技术是采用Owin实现OpenIdConnect的客户端,构建过程如下。

首先,在我们现有的测试解决方案中增加一个Asp.Net MVC项目,采用.Net Framework 4.5.2框架,项目名称为IDS4ClientNet4。

然后,在项目中引入如下程序包:

IdentityModel

Microsoft.Owin

Microsoft.Owin.Host.SystemWeb

接下来,在项目中增加Startup.cs文件,代码如下:

using IDS4ClientNet4;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin; using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks; [assembly: OwinStartup(typeof(Startup))]
namespace IDS4ClientNet4
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
}); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:4010",
ClientId = "net4mvcclient",
ClientSecret = "secret3",
RedirectUri = "http://localhost:49816/signin-oidc",//Net4MvcClient's URL PostLogoutRedirectUri = "http://localhost:49816",
ResponseType = "id_token token",
RequireHttpsMetadata = false, Scope = "openid profile myapi", TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "name"
}, SignInAsAuthenticationType = "Cookies", Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
n.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); return Task.FromResult(0);
},
RedirectToIdentityProvider = n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
if (id_token_claim != null)
{
n.ProtocolMessage.IdTokenHint = id_token_claim.Value;
}
}
return Task.FromResult(0);
}
} }); }
}
}

注意,这里使用的ResponseType是id_token token,不是code。

修改HomeController,将About设置为[Authorize],增加访问WebApi和Logout功能:

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc; namespace IDS4ClientNet4.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
} [Authorize]
public ActionResult About()
{
ViewBag.Message = "Your application description page."; return View();
} public async Task<ActionResult> WebApi()
{
var user = User as ClaimsPrincipal;
var accessToken = user.FindFirst("access_token").Value; var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.GetAsync("http://localhost:5153/WeatherForecast");
string content;
if (!response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
ViewBag.Json = content;
}
else
{
content = await response.Content.ReadAsStringAsync();
ViewBag.Json = JArray.Parse(content).ToString();
} return View();
} public ActionResult Logout()
{
System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut();
return Redirect("/");
}
}
}

About的视图About.cshtml如下:

@using System.Security.Claims;
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3> <p>Use this area to provide additional information.</p>
<dl>
@foreach (var claim in (User as ClaimsPrincipal).Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>

视图WebApi.cshtml如下:

<pre>@ViewBag.Json</pre>

下面需要使用认证管理应用增加一个客户端,名称为net4mvcclient,Client Secret为secret3。需要注意的是,这个客户端需要设置为隐式模式(Implicit)



设置完成后,将解决方案的启动项目设置为多项目启动,同时启动客户端和Web Api:



启动项目,访问关于页面,会跳转到认证服务的登录页面,登录完成后,会显示用户的详细信息。访问WebApi页面,可以获取Api返回的数据:

通过这个项目我们验证了.Net Framework与认证服务集成的方案。

Identity Server 4 从入门到落地(八)—— .Net Framework 客户端的更多相关文章

  1. Identity Server 4 从入门到落地(九)—— 客户端User和Role的解析

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  2. Identity Server 4 从入门到落地(十)—— 编写可配置的客户端和Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  3. Identity Server 4 从入门到落地(十一)—— Docker部署

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  4. Identity Server 4 从入门到落地(十二)—— 使用Nginx集成认证服务

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  5. Identity Server 4 从入门到落地(五)—— 使用Ajax访问Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  6. Identity Server 4 从入门到落地(四)—— 创建Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  7. Identity Server 4 从入门到落地(六)—— 简单的单页面客户端

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  8. Identity Server 4 从入门到落地(七)—— 控制台客户端

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  9. Identity Server 4 从入门到落地(一)—— 从IdentityServer4.Admin开始

    最近项目中需要使用Identity Server 4,以前对这个技术只是有些了解,没有系统研究过,网上相关的资料不少,大多是从编写一个简单的认证服务开始,离能够落地使用有相当的距离,理论学习如何不结合 ...

随机推荐

  1. c#复制数组的多种方法

    方法一:使用for循环 int []pins = {9,3,7,2} int []copy = new int[pins.length]; for(int i =0;i!=copy.length;i+ ...

  2. java中Map及Map.Entry详解

    Map是java中的接口,Map.Entry是Map的一个内部接口. Map提供了一些常用方法,如keySet().entrySet()等方法. keySet()方法返回值是Map中key值的集合:e ...

  3. 什么是SimpleNVR流媒体服务器软件?

    SimpleNVR是一款新兴流媒体服务器应用软件,占用内存少,无插件.跨平台,应用非常广泛,操作简单易上手,同时还支持一键观看,十分便捷.另外,跟其他一般流媒体服务器不同,SimpleNVR支持开发者 ...

  4. Python Excel工具类封装, 给excel表头搞点颜色

    封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...

  5. Pytest使用pytest-html和allure生成测试报告

    Pytest-html 1.安装命令pip3 install pytest-html,如下图: 执⾏后,会在当前⽬录下⽣成 ⼀个report.html的⽂件,打开后会展示详细的测试报告,执行该命令py ...

  6. SpringCloud升级之路2020.0.x版-32. 改进负载均衡算法

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 在前面一节,我们梳理了实现 Feign 断路器以及线程隔离的思路,这一节,我们先不看如何源 ...

  7. Rancher 下图形界面 搭建 K8S 集群

    首先我们准备4台 2核3G 的 centos 7 温馨提示:先安装好一台 CentOS 的虚拟机,并且安装好 docker,永久关闭防火墙. 再这个基础上我们分别克隆出四台 Rancher.K8S1. ...

  8. 如何保证redis中存放的都是热点数据

    当redis使用的内存超过了设置的最大内存时,会触发redis的key淘汰机制,在redis 3.0中有6种淘汰策略: noeviction: 不删除策略.当达到最大内存限制时, 如果需要使用更多内存 ...

  9. Vue3学习(十一)之 table表格组件的使用

    一.前言 大约有两周没学习更文,不是懒,而是没心情,相亲路屡战屡败,着实很影响心情. 我想这世上对我而言,最难的事,莫过于恋爱结婚了,再一次经历了见光死的高光时刻. 二.又见Ant Design Vu ...

  10. 大一C语言学习笔记(3)---对于程序员来说,学历和能力,到底哪个重要?

    在高考失利后,我合理地萎靡一段时间,振作起来之后选择了我憧憬了10年的计算机专业---软件工程.但由于分数受限,也是选择了二本普通院校黑科技(我当然爱她,我的母校),而因为学历上的自卑,让我有了想考研 ...