前言

  上一篇文章<学习OIDC>介绍了OIDC协议,本篇开始我们就来具体来学习OIDC的具体实现IdentityServer4 学习。

一、IdentityServer4 是什么?

  IdentityServer4是用于ASP.NET Core的OpenID Connect和OAuth 2.0框架。

  可以构建(或重新使用)包含登录和注销页面的应用程序,IdentityServer中间件会向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与其对话。

  

   可以在应用程序中使用以下功能:

    • 身份验证即服务

      所有应用程序(Web,本机,移动,服务)的集中式登录逻辑和工作流。IdentityServer是OpenID Connect 的官方认证实现

    • 单点登录/退出

      多种应用程序类型的单点登录(注销)

    • API的访问控制

      为各种类型的客户端(例如,服务器到服务器,Web应用程序,SPA和本机/移动应用程序)的API发出访问令牌

    • 联合网关

      支持外部身份提供程序,例如Azure Active Directory,Google,Facebook等。这使您的应用程序免受如何连接到这些外部提供程序的详细信息的影响。

二、简单使用示例

先创建项目目录结构(如下图)

 1、IdentityServer 认证服务实现

  a) 创建一个空的WebApi项目-cz.IdentityServer,并添加IdentityServer4项目引用:如下图:

Install-Package IdentityServer4

  b) 要启用IdentityServer服务,不仅要把 IdentityServer 注册到容器中, 还需要配置一下内容:

    • Authorization Server 保护了哪些 API (资源);
    • 哪些客户端 Client(应用) 可以使用这个 Authorization Server;

    • 指定可以使用 Authorization Server 授权的 Users(用户)

   创建文件 InMemoryConfig.cs,用于设置以上相关内容:    

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace cz.IdentityServer
{
public class InMemoryConfig
{
public static IEnumerable<IdentityResource> GetIdentityResourceResources()
{
return new List<IdentityResource>
{
//必须要添加,否则报无效的scope错误
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
} /// <summary>
/// api资源列表
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
//可访问的API资源(资源名,资源描述)
return new List<ApiResource>
{
new ApiResource("goods", "Goods Service"),
new ApiResource("order", "Order Service")
};
} /// <summary>
/// 客户端列表
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "clientGoods", //访问客户端Id,必须唯一
//使用客户端授权模式,客户端只需要clientid和secrets就可以访问对应的api资源。
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {
"goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
},
new Client
{
ClientId = "clientOrder",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
//这里使用的是通过用户名密码和ClientCredentials来换取token的方式. ClientCredentials允许Client只使用ClientSecrets来获取token. 这比较适合那种没有用户参与的api动作
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}
};
} /// <summary>
/// 指定可以使用 Authorization Server 授权的 Users(用户)
/// </summary>
/// <returns></returns>
public static IEnumerable<TestUser> Users()
{
return new[]
{
new TestUser
{
SubjectId = "",
Username = "cba",
Password = "cba"
},
new TestUser
{
SubjectId = "",
Username = "chaney",
Password = ""
}
};
}
}
}

    GetApiResources:这里指定了name和display name, 以后api使用authorization server的时候, 这个name一定要一致

    GetClients: 认证客户端列表

    Users: 这里的内存用户的类型是TestUser, 只适合学习和测试使用, 实际生产环境中还是需要使用数据库来存储用户信息的, 例如接下来会使用asp.net core identity. TestUser的SubjectId是唯一标识.

   在Startup.cs中启用IdentityServer服务

      修改StartUp.cs中的ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
.AddTestUsers(InMemoryConfig.Users().ToList())
.AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResourceResources())
.AddInMemoryClients(InMemoryConfig.GetClients());
}

    修改StartUp.cs中的Configure方法    

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting();
       //启用IdentityServer
app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

   运行此项目,打开浏览器访问http://localhost:5600/.well-known/openid-configuration你将会看到IdentityServer的各种元数据信息。

    

  c) 引入QuickStartUI界面

   IdentityServer提供了一套UI以使我们能快速的开发具有基本功能的认证/授权界面,下载地址:QuickStartUI

   下载后,把QuickStartUI中:wwwroot、Quickstart、Views拷贝到项目中,如下结构:、

   

   修改Statup.cs内容如下:

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(); services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfig.Users().ToList())
.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
.AddInMemoryClients(InMemoryConfig.GetClients());
} // 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.UseStaticFiles(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

   运行如下效果:

   

 2、IdentityServer 集成Api服务

   a)添加web api项目cz.Api.Order,并添加nuget中安装IdentityServer4.AccessTokenValidation ,如下图:  

命令:Install-Package IdentityServer4.AccessTokenValidation 

    

   b) 修改StartUp.cs文件    

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.UseHttpsRedirection(); app.UseRouting();
       //启用Authentication中间件
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

  c) 对cz.Api.Order项目中WebApi添加[Authorize]特性    

[Route("identity")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
}

   d) 此时调用该服务时提示401,如下图:

    

  e) 可以通过client信息获取token,然后通过Header传递token 调用weapi

  

   

三、总结

  通过上面的例子,很简单就实现了WepApi的认证授权效果;主要步骤如下:

  • 前往IdentityServer服务中,设置需要请求的ApiResource,Client,User内容
  • WebApi服务设置IdentityServerAuthentication地址(对接认证服务)
  • 调用WebApi时,先在IdentityServer中根据设置的方式获取access token,再带着access token请求接口才能正常访问

四、后续

  IdentityServer包含的内容有很多,准备从多个内容来学习记录使用IdentityServer的功能:SSO(单点登录)、各种授权模式使用、三方账号登录……

  最后来实现一个自己的统一身份认证服务

认证授权:IdentityServer4的更多相关文章

  1. 基于IdentityServer4 实现.NET Core的认证授权

    IdentityServer4是什么? IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现. OpenID ...

  2. .net core gRPC与IdentityServer4集成认证授权

    前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...

  3. 授权认证(IdentityServer4)

    区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...

  4. 一看就懂的IdentityServer4认证授权设计方案

    查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...

  5. Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务

    在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka ...

  6. .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

    原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...

  7. 一站式WebAPI与认证授权服务

    保护WEBAPI有哪些方法? 微软官方文档推荐了好几个: Azure Active Directory Azure Active Directory B2C (Azure AD B2C)] Ident ...

  8. 一款基于.NET Core的认证授权解决方案-葫芦藤1.0开源啦

    背景 18年公司准备在技术上进行转型,而公司技术团队是互相独立的,新技术的推动阻力很大.我们需要找到一个切入点.公司的项目很多,而各个系统之间又不互通,导致每套系统都有一套登录体系,给员工和客户都带来 ...

  9. Owin中间件搭建OAuth2.0认证授权服务体会

    继两篇转载的Owin搭建OAuth 2.0的文章,使用Owin中间件搭建OAuth2.0认证授权服务器和理解OAuth 2.0之后,我想把最近整理的资料做一下总结. 前两篇主要是介绍概念和一个基本的D ...

随机推荐

  1. CI4框架应用一 - 环境搭建

    CI框架 (codeigniter)算是一个古老的框架了,由于在工作中一直在使用这个框架,还是比较有感情的.我对CI的感觉就是,简单易用,学习曲线平滑,对于新手友好. 目前CI框架已经更新到CI4了, ...

  2. MYSQL 按某个字段分组,然后取每组前3条记录

    先初始化一些数据,表名为 test ,字段及数据为: SQL执行结果为:每个 uid  都只有 3 条记录.   SQL语句为: SELECT   * FROM   test main WHERE   ...

  3. Nginx.conf参数配置详解

    Nginx的配置文件nginx.conf配置详解如下: user nginx nginx; #Nginx用户及组:用户 组.window下不指定 worker_processes 8; #工作进程:数 ...

  4. 会话机制,Cookie和Session详解

    转载自:https://www.cnblogs.com/whgk/p/6422391.html 很大一部分应该知道什么是会话机制,也能说的出几句,我也大概了解一点,但是学了之后几天不用,立马忘的一干二 ...

  5. 19、State 状态模式

    “人有悲欢离合,月有阴晴圆缺”,包括人在内,很多事物都具有多种状态,而且在不同状态下会具有不同的行为,这些状态在特定条件下还将发生相互转换.就像水,它可以凝固成冰,也可以受热蒸发后变成水蒸汽,水可以流 ...

  6. 用Unity3D实现太阳系仿真

    用Unity3D模拟太阳系仿真 模拟要求 写一个程序,实现一个完整的太阳系, 其他星球围绕太阳的转速必须不一样,且不在一个法平面上. 操作步骤 1.创建如下结构 sun 里包括8大行星, 并且设置好距 ...

  7. 基于.NetCore3.1系列 —— 日志记录之自定义日志组件

    一.前言 回顾:日志记录之日志核心要素揭秘 在上一篇中,我们通过学习了解在.net core 中内置的日志记录中的几大核心要素,在日志工厂记录器(ILoggerFactory)中实现将日志记录提供器( ...

  8. 初识ABP vNext(1):开篇计划&基础知识

    目录 前言 开始 审计(Audit) 本地化(Localization) 事件总线(Event Bus) 多租户(multi-tenancy technology) DDD分层 实体(Entity) ...

  9. Kubernetes实战总结 - 自定义Prometheus

    一.概述 首先Prometheus整体监控结构略微复杂,一个个部署并不简单.另外监控Kubernetes就需要访问内部数据,必定需要进行认证.鉴权.准入控制, 那么这一整套下来将变得难上加难,而且还需 ...

  10. 使用MSF通过MS17-010获取系统权限

    ---恢复内容开始--- Step1:开启postgresql数据库: /etc/init.d/postgresql start Step2:进入MSF中,搜索cve17-010相关的exp: sea ...