当前位置: 移动技术网 > IT编程>开发语言>.net > IdentityServer4实现.Net Core API接口权限认证(快速入门)

IdentityServer4实现.Net Core API接口权限认证(快速入门)

2020年06月23日  | 移动技术网IT编程  | 我要评论

东北农业大学教务处,贤贤网,jar小说

什么是identityserver4

官方解释:identityserver4是基于asp.net core实现的认证和授权框架,是对openid connect和oauth 2.0协议的实现。

通俗来讲,就是服务端对需要认证授权的资源(客户端请求资源)在外层使用identityserver4框架进行封装加壳,用户只能通过获取identityserver4颁发的token令牌才能进行资源访问。

下面开始进入正题,如何快速搭建实现api接口鉴权。

准备:1.下载准备netcore sdk环境

2.本文开发环境为vs2019,部分代码可能和之前的版本不同。

第一步,新建权限认证服务项目,本文以net core api项目模板为例(也可以选择其他模板)

第二步,添加identityserver4 nuget程序包。不同版本依赖的netcoe sdk环境不同,需手动选择合适版本。

这里提醒一下,有些同学的系统可能添加nuget程序包时,发现无法找到程序包。我们这里找出了解决方法,点击nuget程序包添加页面的右上角设置按钮,看到如下页面,手动添加如下的nuget.org,然后重新搜索即可。

第三步,添加identityserver4配置管理类。本文以用户密码授权模式为例。

public class config
  {
    /// <summary>
    /// 定义资源范围
    /// </summary>
    public static ienumerable<apiresource> getapiresources()
    {
      return new list<apiresource>
      {
        new apiresource("api1", "我的第一个api")
      };
    }

    /// <summary>
    /// 定义访问的资源客户端
    /// </summary>
    /// <returns></returns>
    public static ienumerable<client> getclients()
    {
      return new list<client>
      {
        new client{
          clientid="client",//定义客户端id
          clientsecrets=
          {
            new secret("secret".sha256())//定义客户端秘钥
          },
          allowedgranttypes=granttypes.resourceownerpassword,//授权方式为用户密码模式授权,类型可参考granttypes枚举
          allowedscopes={ "api1"}//允许客户端访问的范围

        }
       };
    }

    /// <summary>
    /// 这个方法是来规范tooken生成的规则和方法的。一般不进行设置,直接采用默认的即可。
    /// </summary>
    /// <returns></returns>
    public static ienumerable<identityresource> getidentityresources()
    {
      return new identityresource[]
      {
        new identityresources.openid()
      };
    }
  }

第四步,startup启动类中注册服务中间件

// this method gets called by the runtime. use this method to add services to the container.
    public void configureservices(iservicecollection services)
    {
      services.addidentityserver()//注册服务
        .adddevelopersigningcredential()
        .addinmemoryapiresources(config.getapiresources())//配置类定义的授权范围
        .addinmemoryclients(config.getclients())//配置类定义的授权客户端
        .addtestusers(new list<testuser> { new testuser { username = "admin", password = "123456", subjectid = "001", isactive = true } });//模拟测试用户,这里偷懒了,用户可以单独管理,最好不要直接在这里new
      services.addcontrollers();
    }

    // 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.useidentityserver();//添加中间件
      
      app.usehttpsredirection();

      app.userouting();

      app.useauthorization();

      app.useendpoints(endpoints =>
      {
        endpoints.mapcontrollers();
      });
    }

应用程序默认的端口号有两种:1.http://localhost:5000 2.https://localhost:5001.

到这里,identityserver4鉴权服务已经简单搭建完成。我们直接在vs中启动项目。并在端口号后面加上/.well-known/openid-configuration,出现如下页面则表示配置成功。

第五步,postman模拟请求获取token(当然这一步非必须,对postman感兴趣的同学可以试一试)

我们都知道identityserver4需要客户端先访问鉴权服务获取token令牌,才能进一步访问加权的服务器资源。我们这里先通过postman模拟客户端请求,获取token。(postman工具大家可以网上下载,也可以使用谷歌自带的postman插件)

1.使用postman请求token时,有个地方需要注意下:

很多同学在使用https请求时,即请求https://localhost:5001,会发现无法成功。因为postman默认把ssl证书认证打开了,我们可以手动关闭掉。找到postman页面右上方的小扳手图标,进入设置页面找到ssl关掉即可。当然同学们直接使用http://localhost:5000请求就无需设置ssl.

2.请求参数

这里的参数value就是我们在鉴权服务配置类设置的client和testuser信息。

grant_type为授权类型,本文我们使用的是用户密码模式,所以这里填password.

这里我们看到,我们已成功模拟请求获取了token。大功告成,鉴权服务已验证可用,我们赶紧去发布部署吧。

第六步,鉴权服务发布部署。

.net core发布模式有三种:

1.框架依赖+可移植

2.框架依赖+运行时环境(带可执行程序exe)

3.独立部署

简单来说,框架依赖模式发布的程序包,都需要部署环境自带.net core等运行环境;而独立部署则不需要考虑,发布包已经包含了运行环境,直接部署即可。

下面本文以框架依赖+可移植发布,做简单介绍。

发布完成后,我们会在发布路径中看到程序dll.我们找到发布路径,通过cmd命令窗口:dotnet xxx.dll可直接启动。

如上,则表示启动成功。(如果其他发布模式,直接双击发布包中可执行exe文件即可启动)

鉴权服务部署完成后,我们api接口如何使用呢,下面开始正式介绍。

第一步:新建web api项目

添加nuget程序包

第二步:配置启动类

public void configureservices(iservicecollection services)
    {
      //注册服务
      services.addauthentication("bearer")
        .addidentityserverauthentication(x =>
        {
          x.authority = "http://localhost:5000";//鉴权服务地址
          x.requirehttpsmetadata = false;
          x.apiname = "api1";//鉴权范围
        });
      services.addcontrollers();
    }

    public void configure(iapplicationbuilder app, iwebhostenvironment env)
    {
      if (env.isdevelopment())
      {
        app.usedeveloperexceptionpage();
      }
      app.useauthentication();//添加鉴权认证
      app.usehttpsredirection();
      app.userouting();
        app.useauthorization();
      app.useendpoints(endpoints =>
      {
        endpoints.mapcontrollers();
      }); 
    }

应用程序默认的端口号有两种:1.http://localhost:5000 2.https://localhost:5001.为了避免端口号冲突被占用,我们可以在program类中修改应用程序启动端口号。

public static ihostbuilder createhostbuilder(string[] args) =>
      host.createdefaultbuilder(args)
      
        .configurewebhostdefaults(webbuilder =>
        {
          webbuilder.useurls("http://*:5555");//设置启动端口号
          webbuilder.usestartup<startup>();
        });

第三步:创建api demo

[route("api/[controller]")]
  [apicontroller]
  public class testcontroller : controllerbase
  {
    // get: api/test
    /// <summary>
    /// 方法加权
    /// </summary>
    /// <returns></returns>
    [authorize]
    [httpget]
    public ienumerable<string> get()
    {
      return new string[] { "value1", "value2" };
    }

    /// <summary>
    /// 方法未加权 可直接访问
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    // get: api/test/5
    [httpget("{id}", name = "get")]
    public string get(int id)
    {
      return "value";
    }

    /// <summary>
    /// 开放获取token api 接口
    /// </summary>
    /// <returns></returns>
    [httpget("gettoken")]
    public async task<string> gettoken()
    {
      var client = new httpclient();
      var tokenresponse = await client.requestpasswordtokenasync(new passwordtokenrequest
      {
        address = "http://localhost:5000/connect/token",
        clientid = "client",
        clientsecret = "secret",
        scope = "api1",
        username = "admin",
        password = "123456",
      });

      if (tokenresponse.iserror)
      {
        return tokenresponse.error;
      }

      return tokenresponse.accesstoken;

    }
  }

1.接口方法上加上:

[authorize]

相当于对接口加权,只有被授权的用户才能访问(即获取token的用户)。此时上文中接口api/test由于被加权,请求时会报错;但是api/test/1接口未加权,仍可正常请求。

那么我们如何才能访问被加权的接口呢???go next

2.我们这里开放了获取token的接口gettoken(类似于上文中通过postman获取token)

访问被加权的api接口,我们这里需要先请求获取token,然后请求加权接口时带上token参数。

3.请求加权接口

请求加权接口时带上token,接口请求成功!

ok,关于如何快速开发和调试基于identityserver4框架的api接口鉴权服务,至此我们已介绍完毕。

小弟不才,本文中有考虑不周全或错误的地方,欢迎大家指正。

(如果有的同学想通过iis部署api应用程序,这里有个地方需要注意下,需要在iis(功能视图——模块)中添加aspnetcoremodule模块。具体原因本文就不在这里介绍了。)

到此这篇关于identityserver4实现.net core api接口权限认证(快速入门)的文章就介绍到这了,更多相关.net core api权限认证内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

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

相关文章:

验证码:
移动技术网