惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - 小马过河MJ

windows forget jenkins password. 转载(Asp.net Core 中试使用ZKWeb.System.Drawing) EFCore & Mysql migration on Production HTML to PDF pechkin Log4net 为MVC 添加下载权限 辞职 MiniProfiler Android Studio 设置LogCat 颜色 运用Swagger 添加WebAPI 文档 给现有MVC 项目添加 WebAPI Summernote async await 跨域调用WebApi MVC 伪静态 设置EntityFramework 在开发时自动更新数据库 PagedList.MVC 应用 MVC 自定义错误处理 SQL Server 索引结构及其使用(四)[转] SQL Server 索引结构及其使用(三)[转]
Identity Server introspect 调用 /connect/introspect
小马过河MJ · 2020-05-05 · via 博客园 - 小马过河MJ

IdentityServer document is not write clear on this part. so it really confuse me and put me on several hours to resovle this problem.

1. 我的Identity Server Config

public class Config
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("Library.Api","Library Api")
                {
                    ApiSecrets = {new Secret("secret".Sha256())} ,
                    Scopes = { new Scope("api1")}

                }
            };

        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            // client credentials client
            return new List<Client>
            {
                #region ClientCredentials
                // machine to machine client
                new Client
                {
                    ClientId = "client.identity",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    // scopes that client has access to
                    AllowedScopes = { "api1" }
                },
                #endregion 

                #region  ResourceOwnerPassword
                // resource owner password grant client
                new Client
                {
                    ClientId = "password.identity",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    AccessTokenLifetime = 2592000,          //15天
                    //AccessTokenLifetime = 60,          //测试60秒过期
                    SlidingRefreshTokenLifetime = 2592000,  //30天
                    AllowOfflineAccess = true,              //返回refreshToken
                    AlwaysSendClientClaims = true,          //
                    UpdateAccessTokenClaimsOnRefresh = true,
                    AbsoluteRefreshTokenLifetime = 0,       // refreshToken不过期
                    RefreshTokenExpiration = TokenExpiration.Sliding,
                    AlwaysIncludeUserClaimsInIdToken = true,
                    ClientSecrets ={
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = {
                        "api1",
                        StandardScopes.OfflineAccess, //如果要获取refresh_tokens ,必须在scopes中加上OfflineAccess
                        StandardScopes.OpenId,//如果要获取id_token,必须在scopes中加上OpenId和Profile,id_token需要通过refresh_tokens获取AccessToken的时候才能拿到(还未找到原因)
                        StandardScopes.Profile//如果要获取id_token,必须在scopes中加上OpenId和Profile
                      },
                },
                #endregion
                
            };
        }

    }

2. 直接调用 /connect/introspect

官网文档:

POST /connect/introspect
  Authorization: Basic sValue
  
  token=<token>

主要问题就是 sValue是你定义的Api Resource的名字和ApiSecrets. 但是需要将他们转成Base64的字符

var sValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", "Library.Api", "secret")));

这样你就可以在Postman上进行调用

2. 通过代码调用

        public async Task<ActionResult> ValidToken(string token)
        {
            ApiResultModel apiResult = new ApiResultModel();

            var CurrentRequest = httpContextAccessor.HttpContext.Request;
            string sUrl = CurrentRequest.Scheme + "://" + CurrentRequest.Host.Value;

            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync(sUrl);

            var result = await client.IntrospectTokenAsync(new TokenIntrospectionRequest
            {
                Address = disco.IntrospectionEndpoint,

                ClientId = "Library.Api", // this is your APi Resource name
                ClientSecret = "secret",  // this is your APi resource secret
                Token = token
            });

            if (result.IsError)
            {
                apiResult.Code = ResultCode.Error;
                apiResult.Data = result.Error;
                return new JsonResult(apiResult);
            }

            apiResult.Code = ResultCode.Success;
            apiResult.Data = result.IsActive;
            return new JsonResult(apiResult);

        }
public class ApiResultModel
    {
        public ResultCode Code { get; set; }
        public string Message { get; set; }
        public object Data { get; set; }

        public ApiResultModel() { }
        public ApiResultModel(ResultCode code,string message,object data)
        {
            Code = code;
            Message = message;
            Data = data;
        }
    }

    public enum ResultCode
    {
        Success = 0,
        Error = 1,
    }

Postman 测试