当前位置: 移动技术网 > IT编程>开发语言>.net > 微服务(入门四):identityServer的简单使用(客户端授权)

微服务(入门四):identityServer的简单使用(客户端授权)

2019年04月27日  | 移动技术网IT编程  | 我要评论

复古婚礼,掌事吧,邦家租赁最新消息

identityserver简介(摘自identity官网)

identityserver是将符合规范的openid connect和oauth 2.0端点添加到任意asp.net核心应用程序的中间件,通常,您构建(或重新使用)一个包含登录和注销页面的应用程序(可能还包括同意,具体取决于您的需要),identityserver中间件向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与之对话。

托管应用程序可以像您希望的那样复杂,但我们通常建议通过只包含与身份验证相关的ui来尽可能地保持攻击面小。

 

 client               :客户端,从identityserver请求令牌,用户对用户身份校验,客户端必须先从identityserver中注册,然后才能请求令牌。

 sources           :每个资源都有自己唯一的名称,就是文中所定义的api1服务名称,indentity会验证判定是否有访问该资源的权限。

 access token  :访问令牌,由identityserver服务器签发的,客户端使用该令牌进行访问拥有权限的api

 

 

oauth 2.0四种授权模式(granttype)

  •  客户端模式(client_credentials)
  •  密码模式(password)
  •  授权码模式(authorization_code)
  •  简化模式(implicit)

作用

  • 单点登录

        在多个应用程序当中进行统一登录或者注销。

  • api访问控制
    • 为各种类型的客户端(如服务器到服务器、web应用程序、spa和本机/移动应用程序)颁发api访问令牌。
  • 联盟网关

          支持外部身份提供商,如azure active directory、google、facebook等。这将使您的应用程序不了解如何连接到这些外部提供商的详细信息。

开发准备

   开发环境             :vs2019 

   identityserver4:2.4.0

  netcore版本       :2.1

客户端授权模式介绍

客户端模式的话是属于identityserver保护api的最基础的方案,我们定义个indentityserver服务以及一个需要保护的api服务,

当客户端直接访问api的话,由于我们的api服务添加了authorization认证,所以必须要到identityserver放服务器上拿到访问令牌,客户端凭借该令牌去对应api服务当中获取想要得到的数据

添加identityserver项目

  1.首先添加新项目,创建asp.net core web 应用程序  创建一个名称为identityserver4test的项目,选择项目类型api  项目进行创建。

 

2.从程序包管理器控制台或者ngget下载identityserver4

  2.1 程序包管理器控制台:install-package identityserver4

  2.2 nuget 的话在对应的程序集,选择nuget输入identityserver4选择对应的版本进行下载安装

  

 

 

3.添加identity server4 配置

   资源定义可以通过多种方式实现,具体的请查阅官方api文档:

 注:1.apiresource("api1","my api"),其中api1代表你的唯一资源名称,在 allowedscopes = { "api1" }当中必须配置上才可以进行访问

 

using identityserver4.models;
using identityserver4.test;
using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;

namespace identityserver4test.indntityconfig
{
    public class identityserverconfig
    {
        /// <summary>
        /// 添加api资源
        /// </summary>
        /// <returns></returns>
        public static ienumerable<apiresource> getresources()
        {
            return new list<apiresource>
            {
          new apiresource("api1","my api") }; } /// <summary> /// 添加客户端,定义一个可以访问此api的客户端 /// </summary> /// <returns></returns> public static ienumerable<client> getclients() { return new list<client> { new client { /// clientid = "client", // 没有交互性用户,使用 客户端模式 进行身份验证。 allowedgranttypes = granttypes.clientcredentials, // 用于认证的密码 clientsecrets = { new secret("123454".sha256()) }, // 客户端有权访问的范围(scopes) allowedscopes = { "api1" } } }; } } }

 

4.在startup当中注入identityserver4 服务

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using identityserver4.models;
using identityserver4.test;
using identityserver4test.indntityconfig;
using microsoft.aspnetcore.builder;
using microsoft.aspnetcore.hosting;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using microsoft.extensions.logging;
using microsoft.extensions.options;

namespace identityserver4test
{
    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.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
            // 在di容器中注入identityserver服务
            services.addidentityserver()
         
        .addinmemoryapiresources(identityserverconfig.getresources())//添加配置的api资源
        .addinmemoryclients(identityserverconfig.getclients())//添加客户端,定义一个可以访问此api的客户端
            .adddevelopersigningcredential();
            

        }
        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }
            //添加identityserver中间件到http管道
            app.useidentityserver();
            //app.usemvc();
        }
    }
}

5.此时启动程序输入 可以得到如下网站,这是identity server4 提供的配置文档

6.用postman请求获取access_token

  

标注:body 当中的参数

        grant_type    :对应api allowedgranttypes 类型表示授权模式

        client_id        : 对应clentid 

        client_secret: 客户端秘钥

       

7.拿到token以后就可以根据token去访问我们的服务程序,服务程序,首先也是创建一个webapi程序,并且从nuget下载所需的依赖

  •    identityserver4.accesstokenvalidation(程序报管理器的话加上install-package identityserver4.accesstokenvalidation)

  7.1 配置authentication,并且添加    app.useauthentication();到http管道当中

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.builder;
using microsoft.aspnetcore.hosting;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using microsoft.extensions.logging;
using microsoft.extensions.options;

namespace indentityserverclienttest
{
    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.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
             //注入authentication服务
            services.addauthentication("bearer")
            
               .addidentityserverauthentication(options =>
               {
                   options.authority = "http://localhost:3322";//identityserver服务地址
                   options.apiname = "api1"; //服务的名称,对应identity server当中的api资源名称,如果客户端得到的token可以访问此api的权限才可以访问,否则会报401错误
                   options.requirehttpsmetadata = false;
               });

        }

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }
            //添加authentication中间件到http管道
            app.useauthentication();
            app.usemvc();
        }
    }
}

7.2 引用microsoft.aspnetcore.authorization;命名空间,添加authorize认证

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.authorization;
using microsoft.aspnetcore.mvc;

namespace indentityserverclienttest.controllers
{
    [route("api/[controller]")]
    [apicontroller]
    [authorize]
    public class valuescontroller : controllerbase
    {
        // get api/values
        [httpget]
        public actionresult<ienumerable<string>> get()
        {
            return new string[] { "value1", "value2" };
        }

        // get api/values/5
        [httpget("{id}")]
        public actionresult<string> get(int id)
        {
            return "value";
        }

        // post api/values
        [httppost]
        public void post([frombody] string value)
        {
        }

        // put api/values/5
        [httpput("{id}")]
        public void put(int id, [frombody] string value)
        {
        }

        // delete api/values/5
        [httpdelete("{id}")]
        public void delete(int id)
        {
        }

        // delete api/values/5
        [route("send")]
        [httpget]
        public string send()
        {
            return "成功了";

        }

    }
}

7.3. 直接访问的话会报401错误

 

7.4 在请求头当中添加authorization 参数,参数值为bearer加上空格 加上咱们刚才获取到的access_token 请求成功!~~

 

 

快速入口:

快速入口: 

快速入口: 

快速入口:微服务(入门四):identityserver的简单使用(客户端授权) 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网