前言

 上一篇文章介绍了IdentityServer4的各种授权模式,本篇继续介绍使用IdentityServer4实现单点登录效果。

单点登录(SSO)

 SSO( Single Sign-On ),中文意即单点登录,单点登录是一种控制多个相关但彼此独立的系统的访问权限,拥有这一权限的用户可以使用单一的ID和密码访问某个或多个系统从而避免使用不同的用户名或密码,或者通过某种配置无缝地登录每个系统。

 概括就是:一次登录,多处访问

案例场景:

 1、提供资源服务(WebApi):订单:Order(cz.Api.Order)、商品:Goods(cz.Api.Goods)……

 2、业务中存在多个系统:门户系统、订单系统、商品系统……

 3、实现用户登录门户后,跳转订单系统、商品系统时,不需要登录认证(单点登录效果)

一、环境准备:

 调整项目如下图结构:

 

在身份认证项目(cz.IdentityServer)中InMemoryConfig中客户端列表中添加以下客户端内容:(其他内容同上一篇设置相同)

new Client
{
ClientId = "main_client",
ClientName = "Implicit Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
RedirectUris = { "http://localhost:5020/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5020/signout-callback-oidc" },
//是否显示授权提示界面
RequireConsent = true,
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
},
new Client
{
ClientId = "order_client",
ClientName = "Order Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
RedirectUris = { "http://localhost:5021/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5021/signout-callback-oidc" },
//是否显示授权提示界面
RequireConsent = true,
},
new Client
{
ClientId = "goods_client",
ClientName = "Goods Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = { "http://localhost:5022/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5022/signout-callback-oidc" },
//是否显示授权提示界面
RequireConsent = true,
AllowedScopes = {
"goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}

二、程序实现:

 1、订单、商品Api项目:

  a)订单API项目调整:添加Nuget包引用:

Install-Package IdentityServer4.AccessTokenValidation

  b)调整Statup文件:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); //IdentityServer
services.AddMvcCore()
.AddAuthorization(); //配置IdentityServer
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.RequireHttpsMetadata = false; //是否需要https
options.Authority = $"http://localhost:5600"; //IdentityServer授权路径
options.ApiName = "order"; //需要授权的服务名称
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

  c)添加控制器:OrderController

namespace cz.Api.Order.Controllers
{
[ApiController]
[Route("[controller]")]
  [Authorize]
  public class OrderController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Order1", "Order2", "Order3", "Order4", "Order5", "Order6", "Order7", "Order8", "Order9", "Order10"
}; private readonly ILogger<OrderController> _logger; public OrderController(ILogger<OrderController> logger)
{
_logger = logger;
}
     //模拟返回数据
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}

  d)商品项目同步调整,调整Api和方法

 2、门户项目:

  添加Nuget引用:

Install-Package IdentityServer4.AccessTokenValidation
Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect

  a)调整HomeController如下内容:

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[Authorize]
public IActionResult Index()
{
//模拟返回应用列表
List<AppModel> apps = new List<AppModel>();
apps.Add(new AppModel() { AppName = "Order Client", Url = "http://localhost:5021" });
apps.Add(new AppModel() { AppName = "Goods Client", Url = "http://localhost:5022" });
return
View(apps);
}
[Authorize]
public IActionResult Privacy()
{
return View();
}
public IActionResult Logout()
{
return SignOut("oidc", "Cookies");
} }

  b)调整主页视图: 

@model List<AppModel>
@{
ViewData["Title"] = "Home Page";
}
<style>
.box-wrap {
text-align: center;
/* background-color: #d4d4f5;*/
overflow: hidden;
} .box-wrap > div {
width: 31%;
padding-bottom: 31%;
margin: 1%;
border-radius: 10%;
float: left;
background-color: #36A1DB;
}
</style>
<div class="text-center">
<div class="box-wrap">
@foreach (var item in Model)
{
<div class="box">
<a href="@item.Url" target="_blank">@item.AppName</a>
</div>
}
</div>
</div>

  c)调整Statup文件中ConfigureServices方法:    

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
});
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddControllersWithViews();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5600";
options.ClientId = "main_client";
options.ClientSecret = "secret";
options.ResponseType = "id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
//事件
options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents()
{
//远程故障
OnRemoteFailure = context =>
{
context.Response.Redirect("/");
context.HandleResponse();
return Task.FromResult(0);
},
//访问拒绝
OnAccessDenied = context =>
{
//重定向到指定页面
context.Response.Redirect("/");
//停止此请求的所有处理并返回给客户端
context.HandleResponse();
return Task.FromResult(0
);
},
};
});

}

 3、订单、商品客户端项目:

  添加Nuget引用:

Install-Package IdentityServer4.AccessTokenValidation
Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect

  a)修改HomeController内容如下:

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
} [Authorize]
public IActionResult Index()
{
return View();
} public async Task<IActionResult> PrivacyAsync()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("http://localhost:5601/order"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var contentgoods = await client.GetStringAsync("http://localhost:5602/goods"); ViewData["Json"] = $"Goods:{contentgoods}\r\n " +
$"Orders:{content}";
return
View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult Logout()
{
return SignOut("oidc", "Cookies");
}
}

  b)调整对应视图内容:


#####Home.cshtml
@{
ViewData["Title"] = "Home Page";
}
@using Microsoft.AspNetCore.Authentication <h2>Claims</h2>
<div class="text-center">
<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>
</div>
<div class="text-center">
<h2>Properties</h2>
<dl>
@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
{
<dt>@prop.Key</dt>
<dd>@prop.Value</dd>
}
</dl>
</div>

#####Privacy.cshtml

@{
ViewData["Title"] = "API Result";
}
<h1>@ViewData["Title"]</h1>

<p>@ViewData["Json"]</p>

  c)Statup中设置客户端信息  

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
});
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddControllersWithViews();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5600";
options.ClientId = "order_client";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("order");
options.Scope.Add("goods");
options.GetClaimsFromUserInfoEndpoint = true;
//事件
options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents()
{
//远程故障
OnRemoteFailure = context =>
{
context.Response.Redirect("/");
context.HandleResponse();
return Task.FromResult(0);
},
//访问拒绝
OnAccessDenied = context =>
{
//重定向到指定页面
context.Response.Redirect("/");
//停止此请求的所有处理并返回给客户端
context.HandleResponse();
return Task.FromResult(0
);
},
};
});

}

 d)商品客户端调整按照以上内容调整类似。

三、演示效果:

   1、设置项目启动如下图:

   2、示例效果:

   

四、总结:

  通过以上操作,整理单点登录流程如下图:

    

  踩坑:当登录取消、授权提示拒绝时,总是跳转错误界面。

    解决办法:客户端定义时,定义事件:对访问拒绝添加处理逻辑。

//事件
options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents()
{
  //远程故障
  OnRemoteFailure = context =>
  {
    context.Response.Redirect("/");
    context.HandleResponse();
    return Task.FromResult(0);
  },
  //访问拒绝
  OnAccessDenied = context =>
  {
    //重定向到指定页面
    context.Response.Redirect("/");
    //停止此请求的所有处理并返回给客户端
    context.HandleResponse();
    return Task.FromResult(0
);
  },
};

GitHub地址:https://github.com/cwsheng/IdentityServer.Demo.git

认证授权:IdentityServer4 - 单点登录的更多相关文章

  1. NET Core 2.0使用Cookie认证实现SSO单点登录

    NET Core 2.0使用Cookie认证实现SSO单点登录 之前写了一个使用ASP.NET MVC实现SSO登录的Demo,https://github.com/bidianqing/SSO.Sa ...

  2. OAuth2.0认证和授权以及单点登录

    https://www.cnblogs.com/shizhiyi/p/7754721.html OAuth2.0认证和授权机制讲解 2017-10-30 15:33 by shizhiyi, 2273 ...

  3. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_02-用户认证技术方案-单点登录

    2 用户认证技术方案 2.1 单点登录技术方案 分布式系统要实现单点登录,通常将认证系统独立抽取出来,并且将用户身份信息存储在单独的存储介质,比如: MySQL.Redis,考虑性能要求,通常存储在R ...

  4. ASP.NET Core 2.0使用Cookie认证实现SSO单点登录

    之前写了一个使用ASP.NET MVC实现SSO登录的Demo,https://github.com/bidianqing/SSO.Sample,这个Demo是基于.NET Framework,.NE ...

  5. 单点登录(十八)----cas4.2.x客户端增加权限控制shiro

    我们在上面章节已经完成了cas4.2.x登录启用mongodb的验证方式. 单点登录(十三)-----实战-----cas4.2.X登录启用mongodb验证方式完整流程 也完成了获取管理员身份属性 ...

  6. Spring Cloud Alibaba 实战(十一) - Spring Cloud认证授权

    欢迎关注全是干货的技术公众号:JavaEdge 本文主要内容: 如何实现用户认证与授权? 实现的三种方案,全部是通过画图的方式讲解.以及三种方案的对比 最后根据方案改造Gateway和扩展Feign ...

  7. 029.[转] SSO单点登录的通用架构实现

    单点登录的通用架构实现 pphh发布于2018年4月26日 http://www.hyhblog.cn/2018/04/26/single_sign_on_arch/ 目录 1. 什么是单点登录 2. ...

  8. SANGFOR AC配置AD域单点登录(一)----AC侧配置

    一.需求 1. AD域单点登录适用于客户内网已有AD域统一管理内网用户,部署AC后,希望AC和AD域结合实现平滑认证.即终端PC开机通过域帐号登录AD域后自动通过AC认证上网,无需再次人为通过AC认证 ...

  9. IdentityServer4实现单点登录统一认证

    什么是单点登录统一认证:假如某公司旗下有10个网站(比如各种管理网站:人事系统啊,财务系统啊,业绩系统啊等),我是该公司一管理员或者用户,按照传统网站模式是这样:我打开A网站 输入账号密码 然后进入到 ...

随机推荐

  1. springboot 新建的时候 pom 第一行出现红叉,项目可以正常运行

    原因 : maven的插件版本的问题,造成与IDE的不兼容 解决办法 :在pom中加上 <maven-jar-plugin.version>3.1.1</maven-jar-plug ...

  2. 2020.5.28 第八篇 Scrum冲刺博客

    Team:银河超级无敌舰队 Project:招新通 项目冲刺集合贴:链接 目录 一.每日站立会议 1.1 会议照片 1.2 项目完成情况 二.项目燃尽图 三.签入记录 3.1 代码/文档签入记录 3. ...

  3. 更换git远程仓库地址

    通过命令直接修改远程仓库地址 git remote 查看所有远程仓库 git remote xxx 查看指定远程仓库地址 git remote set-url origin 你新的远程仓库地址 先删除 ...

  4. 【MySQL】面试官问我:MySQL如何实现无数据插入,有数据更新?我是这样回答的!

    写在前面 马上就是金九银十的跳槽黄金期了,很多读者都开始出去面试了.这不,又一名读者出去面试被面试官问了一个MySQL的问题:向MySQL中插入数据,如何实现MySQL中没有当前id标识的数据时插入数 ...

  5. 使用手机安装Windows系统------DriveDroid

    今天给大家推荐的软件是: DriveDroid 1.说来都是无奈,前一段时间,重装系统结果按完之后进不去系统,然后手贱又把U启动盘给弄坏了 2.本来想这下需要去找同学借个电脑了,然后就想手机可不可以啊 ...

  6. Spark SQL dropDuplicates

    spark sql 数据去重 在对spark sql 中的dataframe数据表去除重复数据的时候可以使用dropDuplicates()方法 dropDuplicates()有4个重载方法 第一个 ...

  7. C++入门记-构造函数和析构函数

    前文回顾 本文档环境基于Vscode + GCC + CodeRunner 关于C++的环境搭建请参考下面链接: C++入门记-大纲 由于本人具有C#开发经验,部分相同的知识就不再赘述了.只列一下需要 ...

  8. python安装wordcloud库报错

    pip install wordcloud 安装成了这样 红彤彤的一片 解决方法 https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 下载对应版 ...

  9. c++ binding code generator based on clang

    google it http://www.swig.org/Doc3.0/CSharp.html http://samanbarghi.com/blog/2016/12/06/generate-c-i ...

  10. Fitness - 07.07

    倒计时177天 运动53分钟,共计8组半,5.5公里.拉伸5分钟. 每组跑步5分钟(6.5KM/h),走路1分钟(5.5KM/h). 感冒+姨妈耽搁了大半月的时间 终于进入第六周的训练了~~!加油~! ...