使用IdentityServer4实现一个简单的Oauth2客户端模式受权

 

一、首先新建一个webAPI项目作为IdentityServer的服务端,提供生成Token的服务,首先修改Startup.cs文件,以下图:web

二、增长一个Config.cs文件,以便于提供资源和认证设置,以下图:api

三、在Startup.cs文件中配置作初始化:ide

四、好了,咱们把网站启动,而后咱们访问http://localhost:5000/.well-known/openid-configuration(http://localhost:5000是个人程序启动地址,能够在Program.cs文件中本身配置。.well-known/openid-configuration是程序的默认配置地址)而后返回以下内容,代表咱们服务端已经没有什么问题了。网站

 

五、而后咱们再单首创建一个Webapi项目来实现调用IdentityServer端获取token实现资源的正常访问.首先设置启动地址:spa

六、设置API控制器受权特性:code

 

七、设置启动配置选项:blog

8.咱们先在Postman中用一个错误的token去访问,结果提示未受权。token

 

九、经过访问IdentityServer提供的endpoint(步骤4图中有标记)地址来获取token,以下图:资源

10.经过获取的token,去访问被限制的资源(即步骤6图中标识的位置),返回成功,即访问成功:string

 

 

附上经过第三方程序来调用token,而后携带token访问API的demo:

using System;
using System.Net.Http;
using IdentityModel.Client;
namespace identityServerClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var discoveryClient=DiscoveryClient.GetAsync("http://localhost:5000").Result;
            if(discoveryClient.IsError)
            {
                Console.WriteLine("there are some errors");
            }
            var tokenClient=new TokenClient(discoveryClient.TokenEndpoint,"client","secret");
            var tokenResponse=tokenClient.RequestClientCredentialsAsync("api").Result;
            if(tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
            }
            else
            {
                Console.WriteLine(tokenResponse.Json);
            }
            var 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);
            }
            Console.ReadLine();


            Console.WriteLine("Hello World!");
        }
    }
}
相关文章
相关标签/搜索