zoukankan      html  css  js  c++  java
  • IdentityServer4[3]:使用客户端认证控制API访问(客户端授权模式)

    使用客户端认证控制API访问(客户端授权模式)

    场景描述

    使用IdentityServer保护API的最基本场景。

    我们定义一个API和要访问API的客户端。客户端从IdentityServer请求AccessToken,然后访问对应的API。

    创建项目
    • IdentityServer的ASP.NET Core Web空项目,端口5000

    • Api的ASP.NET Core Web API项目,端口5001

    • Client的控制台项目

    5.png

    IdentityServer准备工作

    定义API资源

    1.jpg

    定义客户端

    TIM截图20190307150120.jpg

    配置IdentityServer

    TIM截图20190307163327.jpg

    运行IdentityServer项目(自宿主)并在浏览器中输入地址:http://localhost:5000/.well-known/openid-configuration既可以看到IdentityServer的各种元数据信息,可以使用在线json格式化工具显示如下:

    TIM截图20190307152843.jpg

    API准备

    在API控制器上,增加[Authorize]特性(授权)

    TIM截图20190307154700.jpg

    startup增加如下代码:

    TIM截图20190307154726.jpg

    AddAuthentication将身份认证添加到DI,使用"Bearer"方案。AddIdentityServerAuthentication将IdentityServer Token认证处理程序添加到DI,供身份认证服务使用。配置提供Token的基地址为:"http://localhost:5000",不使用https。

    如果此时使用postman访问:http://localhost:5001/api/values,则会得到401的结果

    TIM截图20190307154552.jpg

    创建客户端

    IdentityModel 包括用于发现 IdentityServer 各个终结点(EndPoint)的客户端库。这样只需要知道 IdentityServer 的地址 - 可以从元数据中读取实际的各个终结点地址:

    var client = new HttpClient();
    var disdoc = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
    if (disdoc.IsError)
    {
     Console.WriteLine(disdoc.Error);
    }
    

    获取token

    var tokenResponse = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    {
     Address = disdoc.TokenEndpoint,
     ClientId = "client",
     ClientSecret = "secret",
     Scope = "api1"
    }).Result;
    ​
    if (tokenResponse.IsError)
    {
     Console.WriteLine(tokenResponse.Error);
    }
    else
    {
     Console.WriteLine(tokenResponse.Json);
    }
    

    调用API

    HttpClient httpClient = new HttpClient();
    httpClient.SetBearerToken(tokenResponse.AccessToken);
    var response = httpClient.GetAsync("http://localhost:5001/api/values").Result;
    if (response.IsSuccessStatusCode)
    {
     Console.WriteLine(response.Content.ReadAsStringAsync().Result);
    }
    

    使用postman调用

    TIM截图20190307163755.jpg

    IdentityServer4 中文文档与实战

    IdentityServer4 知多少

    jessetalk视频教程

  • 相关阅读:
    Extjs 4.0 Grid 数据绑定 json 分页 不分页
    [转]AS语言基础
    tig支持中文搜索
    LPC及MudOS简介(一)
    欢送2012
    存储器性能测试
    为什么go语言适合开发网游服务器端
    从一段代码里看FreeBSD与Linux内存分配的不同
    新的开始
    多语言协作与二进制交互
  • 原文地址:https://www.cnblogs.com/vigorous/p/10493949.html
Copyright © 2011-2022 走看看