IdentityServer4專題之五:OpenID Connect及其Client Credentials流程模式

1.基於概念json

OAuth2.0與身份認證協議的角色映射api

 

OpenID Connect 這個協議是2014頒發的,基於OAuth2.0,在這個協議中,ID Token會和Access Token一塊兒發回客戶端應用,它還提供了一個UserInfo這個端點,經過此端點能夠獲取用戶信息,還提供了一級標識身份的scopes和claims(profile、email、address、phone)app

 

這個協議定義了三個流程:asp.net

 

Identity Server4.0的結構圖async

2.三種流程模式ide

IdentityServer上:工具

在startup.cs頁面中ConfiureServices頁面中,應將json config 方式改成code config方式。即按以下方式切換註釋代碼網站

// in-memory, code configui

            builder.AddInMemoryIdentityResources(Config.GetIdentityResources());this

            builder.AddInMemoryApiResources(Config.GetApis());

            builder.AddInMemoryClients(Config.GetClients());

  // in-memory, json config

            //builder.AddInMemoryIdentityResources(Configuration.GetSection("IdentityResources"));

 //builder.AddInMemoryApiResources(Configuration.GetSection("ApiResources"));

//builder.AddInMemoryClients(Configuration.GetSection("clients"));

 

public static class Config

    {

        public static IEnumerable<IdentityResource> GetIdentityResources()

        {

            return new IdentityResource[]

            {

                new IdentityResources.OpenId(),

                new IdentityResources.Profile(),

            };

        }

        public static IEnumerable<ApiResource> GetApis()

        {

            return new ApiResource[]

            {

                new ApiResource("api1", "My API #1")

            };

        }

        public static IEnumerable<Client> GetClients()

        {

            return new[]

            {

                // client credentials flow client

                new Client

                {

                    ClientId = "console client",

                    ClientName = "Client Credentials Client",

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },

                    AllowedScopes = {"api1" }

                }              

            };

        }

   }

 

客戶端控制檯程序代碼:

static async Task Main(string[] args)

        {

            //Discovery endpoint

            Console.WriteLine("Hello World!");

            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");

            if(disco.IsError)

            {

                Console.WriteLine(disco.Error);

                return;

            }

            //Request access token,客戶端必須帶有:ClientCredentials

            var tokenResponse =await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest {

                Address = disco.TokenEndpoint,

                ClientId = "console client",

                ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",

                Scope= "api1"

            });

            if (tokenResponse.IsError)

            {

                Console.WriteLine(tokenResponse.Error);

                return;

            }

            var apiClient = new HttpClient();

            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var response = await apiClient.GetAsync("http://localhost:5002/api/values");

            if (!response.IsSuccessStatusCode)

            {

                Console.WriteLine(response.StatusCode);

            }

            else

            {

                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(content);

             }

asp.net core api資源應用:

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)

        {         

            //使用IdentityServer認證和受權

            services.AddMvcCore().AddAuthorization().AddJsonFormatters();

            services.AddAuthentication("Bearer")

                .AddJwtBearer("Bearer", options =>

                {

                    options.Authority = "http://localhost:5000";

                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";

                });          

          }

           public void Configure(IApplicationBuilder app, IHostingEnvironment env)

           {   //使用identityserver

            app.UseAuthentication();

            app.UseMvc();

           }

  }

 

 

 

[Route("api/[controller]")]

    [Authorize]

    [ApiController]

    public class ValuesController : ControllerBase

    {

        // GET api/values

        [HttpGet]

        public ActionResult<IEnumerable<string>> Get()

        {

            return new string[] { "value1", "value2","value3"};

        }

總結:Client Credentials這種方式,客戶端應用不表明用戶,客戶端應用自己就至關因而資源全部者;一般用於機器對機器的通訊;客戶端也須要身份認證。

可採用工具軟件監控客戶端與服務端的通訊:

 

將獲取的access token放到網站https://jwt.io/,進行解碼,便可以看到token中包含的許多用用信息。

相關文章
相關標籤/搜索