tnblog
首页
视频
资源
登录

IdentityServer4 单点登陆

5822人阅读 2019/12/18 17:02 总访问:450004 评论:0 收藏:0 手机
分类: 笔记

                 

  1.                  
  2. hello 大家好 又见面了 今天给大家分享一下 identityServer4
  3. 首选我们先来了解一下什么是identityServer.
  4. 什么是单点登录统一认证:假如某公司旗下有10个网站(比如各种管理网站:人事系统啊,财务系统啊,业绩系统啊等),我是该公司一管理员或者用户,按照传统网站模式是这样:我打开A网站
  5.  输入账号密码 
  6. 然后进入到A网站办点事,办完之后,我有需要到B网站去办点事,这个时候又需要输入账号密码,假如你还要到C网站办点事,又再需要输入账号密码。。。。。
  7.   为了解决这个问题,所以出现了单点登录统一认证:即 该改管理员 登录了其中一个网站得到了ids4的授权之后,他再登入该公司旗下其他网站的时候不需要在输入账号密码,能够直接进入后台办事! 这就是单点登录统一认证!
  8. 下面咋们就用代码来展示一下
  9. 第一步:新建一个net core 项目,如下图所示
  10. 第二步:引进安装依赖项:IdentityServer4,在项目里面打开工具 找到程序包控制管理台 用install-package IdentityServer4 进行下载
  11. 第三步:打开项目里面的调试如下图 设置该项目的地址
  12. 第四步:新建一个配置文件类:Config.cs  代码如下:
  13. public class Config
  14.     {        // scopes define the resources in your system
  15.         public static IEnumerable<IdentityResource> GetIdentityResources()
  16.         {            return new List<IdentityResource>
  17.             {       new IdentityResources.OpenId(),                
  18.                        new IdentityResources.Profile(),
  19.             };
  20.         }        // clients want to access resources (aka scopes)
  21.         public static IEnumerable<Client> GetClients()
  22.         {            return new List<Client>
  23.             {                // OpenID Connect隐式流客户端(MVC)
  24.                 new Client
  25.                 {
  26.                     ClientId = "mvc",
  27.                     ClientName = "MVC Client",
  28.                     AllowedGrantTypes = GrantTypes.Implicit,//隐式方式
  29.                     RequireConsent=false,//如果不需要显示否同意授权 页面 这里就设置为false
  30.                     RedirectUris = { "http://localhost:5002/signin-oidc" },//登录成功后返回的客户端地址
  31.                     PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },//注销登录后返回的客户端地址
  32.                     AllowedScopes =//下面这两个必须要加吧 不太明白啥意思                    {
  33.                         IdentityServerConstants.StandardScopes.OpenId,
  34.                         IdentityServerConstants.StandardScopes.Profile
  35.                     }
  36.                 }
  37.             };
  38.         }
  39.     }
  40. 第五步: 在Startup.cs的ConfigureServices方法中注入Ids4服务,如下面红色部分代码:
  41. public void ConfigureServices(IServiceCollection services)
  42.         {
  43.            
  44.         }
  45.   在Startup.cs的Configure方法中添加ids4服务中间件(注意要放在UseMvc之前就可以)
  46.   app.UseIdentityServer();
  47.   现在id4的配置基本完成 下面就是要用数据进行测试
  48.  
  49. 添加DbContext类 名字叫:EFContext.cs ,代码如下(其中红色部分是我们待会需要添加的实体类,也就是对应数据库里面的用户表Admin)
  50. public class EFContext : DbContext
  51.     {        public EFContext(DbContextOptions<EFContext> options) : base(options)
  52.         {
  53.         }        #region 实体集  
  54.              
  55.         #endregion
  56.     }
  57.     新建一个实体类 把实体添加到上一个类中,也就是上一个类的红色部分
  58.     public class Admin
  59.     {      public int Id { getset; } 
  60.            public DateTime CreateDate { getset; } 
  61.            public string UserName { getset; } 
  62.            public string Password { getset; } 
  63.            public string Remark { getset; }
  64.     }
  65. 在Startup.cs的ConfigureServices方法中注入 EFContext,如下面红色部分代码
  66. public void ConfigureServices(IServiceCollection services)
  67.         {            
  68.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  69.             services.AddIdentityServer()//Ids4服务                
  70.             .AddDeveloperSigningCredential()
  71.             .AddInMemoryIdentityResources(Config.GetIdentityResources())
  72.             .AddInMemoryClients(Config.GetClients());//把配置文件的Client配置资源放到内存
  73.         }
  74. 接下来,我们就要写Admin这个实体类跟数据库打交道的代码了,比如增删改查,在net中一般交DAL层,在netCore中 一般交services层,要注意的是 netcore的框架是IOC的框架,依赖注入的,所以这个services层需要接口的形式!
  75. 新建一个接口:IAdminService.cs 代码如下:
  76. public interface IAdminService
  77.     {
  78.         Task<Admin> GetByStr(string username, string pwd);//根据用户名和密码查找用户
  79.     }
  80.     新建实现该接口的类AdminService.cs
  81.     public class AdminService:IAdminService
  82.     {        public EFContext db;        public AdminService(EFContext _efContext)
  83.         {
  84.             db = _efContext;
  85.         }
  86.         
  87.         /// <summary>
  88.         /// 验证用户,成功则返回用户信息,否则返回null        
  89.         /// </summary>
  90.         /// <param name="username"></param>
  91.         /// <param name="pwd"></param>
  92.         /// <returns></returns>
  93.         public async Task<Admin> GetByStr(string username, string pwd)
  94.         {
  95.             Admin m=await db.Admin.Where(a => a.UserName == username && a.Password == pwd).SingleOrDefaultAsync();            
  96.             if (m!=null)
  97.             {                
  98.             return m;
  99.             }else
  100.             { 
  101.             return null;
  102.             }
  103.         }
  104.     } 
  105.     
  106.     在Startup.cs的ConfigureServices方法中注入 service层,如下面红色部分代码:   
  107.     public void ConfigureServices(IServiceCollection services)
  108.         {
  109.             services.AddDbContext<EFContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("conn")));//注入DbContext            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  110.             services.AddIdentityServer()//Ids4服务                .AddDeveloperSigningCredential()
  111.                 .AddInMemoryIdentityResources(Config.GetIdentityResources())
  112.                 .AddInMemoryClients(Config.GetClients());//把配置文件的Client配置资源放到内存
  113.           
  114.         }
  115.         
  116.  接下来就是登陆界面  后台新建一个AccountController 控制器
  117.  public class AccountController : Controller
  118.     {        private IAdminService _adminService;//自己写的操作数据库Admin表的service
  119.         private readonly IIdentityServerInteractionService _interaction;        private readonly IClientStore _clientStore;        private readonly IAuthenticationSchemeProvider _schemeProvider;        private readonly IEventService _events;        public AccountController(IIdentityServerInteractionService interaction,
  120.             IClientStore clientStore,
  121.             IAuthenticationSchemeProvider schemeProvider,
  122.             IEventService events,
  123.             IAdminService adminService)
  124.         {
  125.             _interaction = interaction;
  126.             _clientStore = clientStore;
  127.             _schemeProvider = schemeProvider;
  128.             _events = events;
  129.             _adminService = adminService;
  130.         }        /// <summary>
  131.         /// 登录页面        /// </summary>        [HttpGet]        public async Task<IActionResult> Login(string returnUrl=null)
  132.         {
  133.             ViewData["returnUrl"] = returnUrl;            return View();
  134.         }        /// <summary>
  135.         /// 登录post回发处理        /// </summary>        [HttpPost]        public async Task<IActionResult> Login(string userName, string password,string returnUrl=null)
  136.         {
  137.             ViewData["returnUrl"] = returnUrl;
  138.             Admin user = await _adminService.GetByStr(userName, password);            if (user!=null)
  139.             {
  140.                 AuthenticationProperties props= new AuthenticationProperties
  141.                 {
  142.                     IsPersistent = true,
  143.                     ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
  144.                 };                await HttpContext.SignInAsync(user.Id.ToString(), user.UserName, props);                if (returnUrl!=null)
  145.                 {                    return Redirect(returnUrl);
  146.                 }                return View();
  147.             }            else
  148.             {                return View();
  149.             }
  150.         }
  151.     }
  152.     
  153.     前台 新建一个view
  154.    
  155.   @{
  156.     Layout = null;
  157. }<!DOCTYPE html>
  158. <html>
  159. <head>
  160.     <meta name="viewport" content="width=device-width" />
  161.     <title>Login</title>
  162. </head>
  163. <body>
  164.     <div align="center">
  165.         <h1>统一认证登录中心</h1>
  166.         <form action="/Account/Login" method="post">
  167.             用户名:<input type="text" name="userName" /><br />
  168.             密 码:<input type="password" name="password" /><input type="hidden" name="returnUrl" value="@ViewData["returnUrl"]" /> <br />
  169.             <input type="submit" value="登录" />
  170.         </form>
  171.     </div>
  172. </body>
  173. </html>
  174. 综上 IdentityServer4服务端的工作完成 
  175. 接下来就是部署客户端
  176. 前面两步的步骤都一样 同样是建Net Core项目 然后设置地址
  177. 下一步在Startup.cs的ConfigureServices方法中添加(主要用来配置认证中心ids4的及自己作为客户端的认证信息):
  178. public void ConfigureServices(IServiceCollection services)
  179.         {            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  180.             services.AddAuthentication(options =>
  181.                 {
  182.                     options.DefaultScheme = "Cookies";
  183.                     options.DefaultChallengeScheme = "oidc";
  184.                 })
  185.                 .AddCookie("Cookies")
  186.                 .AddOpenIdConnect("oidc", options =>
  187.                 {
  188.                     options.SignInScheme = "Cookies";
  189.                     options.Authority = "http://localhost:5000";
  190.                     options.RequireHttpsMetadata = false;
  191.                     options.ClientId = "mvc";
  192.                     options.SaveTokens = true;
  193.                 });
  194.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  195.         }
  196.         
  197. 在 Configure方法中添加这行代码(需要在UseMvc之前就可以):
  198. app.UseAuthentication();
  199. 综上客户端跟统一认证的信息就配置完了。
  200. 接下来我们把Home控制器上面加上需要验证的标志:[Authorize]

把默认的Index视图页面html代码去掉,改成如下(主要用来显示下授权后拿到的用户信息):

复制代码



  1. @{
  2.     ViewData["Title"] = "Home Page";
  3. }<div align="center"><h1>这里是受保护的客户端首页</h1></div>
  4. <h3>User claims</h3>
  5. <dl>
  6.     @foreach (var claim in User.Claims)
  7.     {        <dt>@claim.Type</dt>
  8.         <dd>@claim.Value</dd>
  9.     }</dl>

最后启动项目就大功告成。

感谢你的观看 我们下期再见

创作不容易给个关注吧!

评价

IdentityServer4退出登录跳转到原页面

IdentityServer4退出登录,注销登录已经封装好了我们使用其实很简单//注销登录 publicIActionResultLogout() { returnSig...

IdentityServer4 【实现单点登录】

今天记录一下 NET Core id4的单点登录虽然现在很流行 也很高大上但是第一次玩 还是很多的坑的。简单来讲就是一个项目登录了...

NET Core【IdentityServer4单点登录】+【退出登录】

第一天接触NetCore,感觉坑很多,其他都还良好比如说我们现在有三个系统,一个是商品系统,一个是订单系统,另外一个就是单...

IdentityServer4 退出登录+EF

登录讲完了 我们讲一下退出登录退出比较简单啦[HttpGet] publicasyncTask&lt;IActionResult&gt;Logout(stringlogoutId) {...

IdentityServer4携带自定义的Claim

identityServer4要携带自定义的Claim,仅仅传递Claim是不行的还需要实现IProfileService方法才行publicclassImplicitProfil...

IdentityServer4实现OAuth2.0四种模式之授权码模式

授权码模式隐藏码模式最大不同是授权码模式不直接返回token,而是先返回一个授权码,然后再根据这个授权码去请求token。这...
每一段路程,都是一种领悟
排名
10
文章
100
粉丝
17
评论
34
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术