IdentityServer4之Clients、Scopes、Claims与Token关联

Stella981
• 阅读 438

IdentityServer4之Clients、Scopes、Claims与Token关联


参考

官方文档clientidentity_resourceapi_resource:三类配置项介绍描述。

打一个不恰当的比喻来描述一下
User:表示自己 。
Client:表示客户经理,能指引或者代办一些业务。
Resource:表示银行,包括identity_resource(银行基本业务)、api_resource(银行特色业务)。多个resource比作多个分行。

user中的
Claims:自身在银行已经有的业务(包括自己YY的业务)。

client中的
Claims、Scopes是客户经理会推荐给你(User)的业务需不需要看自己。
Claims:好比优惠client可以选择给你或者不给。
Scopes:但是推荐给你的某个Scope业务可能与银行已经下线了但是client不知道。

Resource中的
Claims、Scopes、Scopes->Claims:表示银行的业务。

Token:银行认可自己拥有的业务信息。

****User、Client、Resource配置


User配置

new TestUser
{
    SubjectId = "1",
    Username = "ddr",
    Password = "123",
    Claims = new []
    {
        new Claim("name", "ddr"),
        new Claim("get", "get_order"),  //User Claim Type 与 Api Resource中的Claims、Scopes->Claims的Type匹配就会输出到Token
        new Claim("add", "add_order"),
        new Claim("add", "add_account"),
        new Claim("del", "del_all"),
        new Claim("website", "https://ddr.com")
    }
},

Client配置

IdentityServer4之Clients、Scopes、Claims与Token关联

IdentityServer4之Clients、Scopes、Claims与Token关联

Identity Resources配置****

一般不需要改变就是默认的OpenId、Profile、Email、Phone、Address。

{ IdentityServerConstants.StandardScopes.Profile, new[]
                { 
                    JwtClaimTypes.Name,
                    JwtClaimTypes.FamilyName,
                    JwtClaimTypes.GivenName,
                    JwtClaimTypes.MiddleName,
                    JwtClaimTypes.NickName,
                    JwtClaimTypes.PreferredUserName,
                    JwtClaimTypes.Profile,
                    JwtClaimTypes.Picture,
                    JwtClaimTypes.WebSite,
                    JwtClaimTypes.Gender,
                    JwtClaimTypes.BirthDate,
                    JwtClaimTypes.ZoneInfo,
                    JwtClaimTypes.Locale,
                    JwtClaimTypes.UpdatedAt 
                }},
{ IdentityServerConstants.StandardScopes.Email, new[]
                { 
                    JwtClaimTypes.Email,
                    JwtClaimTypes.EmailVerified 
                }},
{ IdentityServerConstants.StandardScopes.Address, new[]
                {
                    JwtClaimTypes.Address
                }},
{ IdentityServerConstants.StandardScopes.Phone, new[]
                {
                    JwtClaimTypes.PhoneNumber,
                    JwtClaimTypes.PhoneNumberVerified
                }},
{ IdentityServerConstants.StandardScopes.OpenId, new[]
                {
                    JwtClaimTypes.Subject
                }}

Api Resource配置****

IdentityServer4之Clients、Scopes、Claims与Token关联

IdentityServer4之Clients、Scopes、Claims与Token关联

过程详解

使用正常方式获取的Token

IdentityServer4之Clients、Scopes、Claims与Token关联

获取的Token详细信息

[
  {
    "type": "nbf",
    "value": "1516248790"
  },
  {
    "type": "exp",
    "value": "1516252390"
  },
  {
    "type": "iss",
    "value": "http://www.ids4.com"
  },
  {
    "type": "aud",
    "value": "http://www.ids4.com/resources"
  },
  {
    "type": "aud",
    "value": "shop"
  },
  {
    "type": "client_id",
    "value": "ro.client"
  },
  {
    "type": "sub",
    "value": "1"
  },
  {
    "type": "auth_time",
    "value": "1516248785"
  },
  {
    "type": "idp",
    "value": "local"
  },
  {
    "type": "get",
    "value": "get_order"
  },
  {
    "type": "add",
    "value": "add_order"
  },
  {
    "type": "add",
    "value": "add_account"
  },
  {
    "type": "scope",
    "value": "account"
  },
  {
    "type": "scope",
    "value": "order"
  },
  {
    "type": "amr",
    "value": "pwd"
  },
  {
    "type": "api1返回",
    "value": "2018-01-18 12:13:15"
  }
]

client没有把优惠给你,client客户经理的Claims中是有ro - get_account但是这项优惠没有取出来,Properties默认设置IdentityServer4之Clients、Scopes、Claims与Token关联 不会返回到Token。

// check for client claims
if (request.ClientClaims != null && request.ClientClaims.Any()) { if (subject == null || request.Client.AlwaysSendClientClaims) { foreach (var claim in request.ClientClaims) { var claimType = claim.Type; if (request.Client.ClientClaimsPrefix.IsPresent()) { claimType = request.Client.ClientClaimsPrefix + claimType; } outputClaims.Add(new Claim(claimType, claim.Value, claim.ValueType)); } } }

new Claim("del", "del_all") 是自己YY出来的Token里也不会有。

/// <summary>
/// Filters the claims based on requested claim types.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="claims">The claims.</param>
/// <returns></returns>
public static List<Claim> FilterClaims(this ProfileDataRequestContext context, IEnumerable<Claim> claims)
{
    return claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
}

claims自己的claims信息。

IdentityServer4之Clients、Scopes、Claims与Token关联

context.RequestedClaimTypes是Api Resource中Claims、Scopes->Claims的信息。

IdentityServer4之Clients、Scopes、Claims与Token关联

client客户经理推荐的123实际在银行已经下线了。

如果获取Token请求包含了 "123" 的scope,但是实际上Resource又不存在就会提示invalid_scope。

foreach (var scope in requestedScopes)
{
    var identity = resources.IdentityResources.FirstOrDefault(x => x.Name == scope);
    if (identity != null)
    {
        if (!client.AllowedScopes.Contains(scope))
        {
            _logger.LogError("Requested scope not allowed: {scope}", scope);
            return false;
        }
    }
    else
    {
        var api = resources.FindApiScope(scope);
        if (api == null || !client.AllowedScopes.Contains(scope))
        {
            _logger.LogError("Requested scope not allowed: {scope}", scope);
            return false;
        }
    }
}

Scope对模块鉴权

参考:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims

Token中带有 scope:order或者scope:account的请求都能访问IdentityController。

Api项目配置

services.AddMvcCore()
    .AddAuthorization(options =>
    {
        options.AddPolicy("Order", policy => policy.RequireClaim("scope","order","account"));
    })
    .AddJsonFormatters();

[Authorize(Policy = "Order")]
public class IdentityController : ControllerBase

IdentityServer4配置后台管理,在github找到一个随机生成数据的后台改成使用读数据库,数据库使用ids4示例生成。时间紧做出来并不好凑合用。

https://github.com/ddrsql/IdentityServer4.Admin

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这