IdentityServer4身份認證授權入門-----客戶端憑據、密碼模式


一.簡介

IdentityServer4 是為ASP.NET Core 系列量身打造的一款基於 OpenID Connect 和 OAuth 2.0 認證框架

特點:

1.認證服務

2.單點登錄登出(SSO)

3.API訪問控制

4.聯合網關

5.專注於定制

6.成熟的開源系統

7.免費和商業支持

二.簡單示例

1.創建ASP.NET Core 3.0 WebAPI項目

執行cmd命令:dotnet new webapi --name IdentityServerCenter

 

 

 2.打開項目

執行cmd命令:code IdentityServerSimple  來打開VS Code

 

 

 3.nuget 安裝IdentityServer4

執行Ctrl+Shift+p鍵 打開Command Palette(命令選項卡)

輸入>nuget Package Manager:Add Package

 

 

 `輸入IdentityServer4  選擇3.1.0

 

 

 安裝完成后

 

 

4.執行命令:dotnet restore( 還原依賴項和工具包)

 

 

 5.創建Config類

using System.Collections.Generic;
using IdentityServer4.Models;

namespace IdentityServerCenter{
    public class Config{
        public static IEnumerable<ApiResource> GetResources()
        {
           return new List<ApiResource>{new ApiResource("api","MyAPI")};           
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>{
            new Client{ClientId="client",AllowedGrantTypes=GrantTypes.ClientCredentials,
            ClientSecrets={new Secret("secret".Sha256())},
            AllowedScopes={"api"}
            }};
        }
    }
}

6.配置Startup類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using IdentityServer4;

namespace IdentityServerCenter
{
    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.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryApiResources(Config.GetResources()).AddInMemoryClients(Config.GetClients());
            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.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseIdentityServer();
 
        }
    }
}

7.配置Progarm類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace IdentityServerCenter
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>().UseUrls("http://localhost:5000");
                });
    }
}

8.運行服務端項目:

執行命令:dotnet run

訪問地址:http://localhost:5000/.well-known/openid-configuration

 

 

 

三.客戶端集成IdentityServer

1.創建項目

執行cmd命令:dotnet new webapi --name ClientCredentialApi

 

 

2. 添加Package

執行命令:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

 

 

3.添加IdentityController類

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ClientCredentialApi.Controllers{
    
    [Route("identity")]
    [Authorize]
    public class IdentityController:ControllerBase{
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(new {Msg="Success",Code=200});
        }
    }
}

4.配置Startup類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ClientCredentialApi
{
    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.AddControllers();


            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.Audience = "api";
            });
        }

        // 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.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

5.配置Program類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ClientCredentialApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>().UseUrls("http://localhost:5001");
                });
    }
}

6.運行項目

執行命令:dotnet restore  dotnet run 

 

 

 7.輸入:http://localhost:5001/identity

401:表示未授權

8.運行服務端和客戶端

使用PostMan來獲取Token

選擇post請求

選擇form-data

client_id:client  client_secret:secret grant_type:client_credentials

 

 

 9.通過Token來驗證

請求地址:http://localhost:5001/identity

請求方式:get

Headers: key:Authorization  value:Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ikt1Ni1YWk9HNWhYYUh3NHdWWGxwSXciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODA4MDYxODIsImV4cCI6MTU4MDgwOTc4MiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiYXBpIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsiYXBpIl19.A7Mj6xanZfZaAartfFNb3Z6unZRxOGSHgUufcyKFAhL5Ojy5GsXeFlZBTWundXKIC5SILWHoafWrOFvVNcGtH4CxDgUDhlyMpkCRBJyPaAInbLIFqlX9HJLqxzqwUa2Y6qVKtmjBE4WQ9fg4cZSNGviEiqBe2nk2T_U-RLF-y3OMZ6tZblpVZrMYsRiUiyjum3jRJBXRJOw1JaG13OLLrKoEIWX43qRtLZT_5bScqcDJmx4gmcTDeZZZrmsoeT4A7Sr_5hFx_UgwD1edoZiikeFRSvUJZAhLJfuFSR72xMAWSmmqq_H8B3Ed158y0aQb_mHgT8zbQZbHHhIEKD94jg

 

 

 

 四.第三方ClientCredential模式調用

1.創建控制台項目

執行cmd命令:dotnet new console -n ThirdPartyDemo

 

 2.添加IdentityModel包

執行cmd命令:dotnet add package IdentityModel

 

 3.開始測試

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

            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = "client",
                ClientSecret = "secret",
                Scope = "api"
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
           

            client.SetBearerToken(tokenResponse.AccessToken);

            var response = await client.GetAsync("http://localhost:5001/identity");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }

 

 

 

錯誤解決:Versioning information could not be retrieved from theNuget package repository. Please try again later.

打開文件:C:\Users\Administrator\.vscode\extensions\jmrog.vscode-nuget-package-manager-1.1.6\out\src\actions\add-methods\fetchPackageVersions.js

 

 

API文檔:http://docs.identityserver.io/en/latest/index.html

中文文檔:http://www.identityserver.com.cn/

代碼地址:https://github.com/CodeInterface/IdentityServerSimple/tree/Simple


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM