IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0架構學習保護API

來源:互聯網
上載者:User

標籤:資訊   情境   cal   book   ons   相關   特性   啟動   disco   

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0架構學習之保護API。

使用IdentityServer4 來實現使用用戶端憑據保護ASP.NET Core Web API 訪問。

IdentityServer4 GitHub: https://github.com/IdentityServer/IdentityServer4

IdentityServer 架構支援以下功能:

驗證服務
所有應用程式(Web,本機,移動,服務)的集中登入邏輯和工作流程。

單點登入/退出
對多種應用程式類型的單點登入和退出。

API的存取控制
針對各種類型的客戶發出針對API的存取權杖,例如伺服器到伺服器,Web應用程式,SPA和本機/行動裝置 App程式。

同盟登入
支援外部身份提供者,如Azure Active Directory,Google,Facebook等。

專註於定製
IdentityServer最重要的部分 - 許多方面可以定製,以滿足你的需要。由於IdentityServer是一個架構,而不是一個封閉產品或SaaS,你可以編寫代碼,使你的系統適應對應的情境。

 

 

IdentityServer實現了以下規範:

OpenID Connect

OpenID Connect Core 1.0
OpenID Connect Discovery 1.0
OpenID Connect Session Management 1.0 - draft 22
OpenID Connect HTTP-based Logout 1.0 - draft 03

OAuth 2.0

OAuth 2.0 (RFC 6749)
OAuth 2.0 Bearer Token Usage (RFC 6750)
OAuth 2.0 Multiple Response Types
OAuth 2.0 Form Post Response Mode
OAuth 2.0 Token Revocation (RFC 7009)
OAuth 2.0 Token Introspection (RFC 7662)
Proof Key for Code Exchange (RFC 7636)

 

主要講解 使用用戶端憑據保護API 。如何保證的你的API 不被其他人擅自訪問?

下面開始正式的執行個體。

建立ASP.NET Core項目及引用IdentityServer4

首先建立一個ASP.NET Core項目IdentityServer4Demo,然後選擇 模板。

 

然後添加引用。

NuGet命令列:

Install-Package IdentityServer4 -Pre

IdentityServer4使用

添加好引用以後我們就可以來使用了。

首先建立一個 Config.cs 類。

定義範圍:

        public static IEnumerable<Scope> GetScopes()        {            return new List<Scope>            {                new Scope                {                    Name = "zeroapi",                    Description = "LineZero ASP.NET Core Web API"                }            };        }

定義用戶端:

        public static IEnumerable<Client> GetClients()        {            return new List<Client>            {                new Client                {                    ClientId = "linezeroclient",                    //使用clientid / secret進行身分識別驗證                    AllowedGrantTypes = GrantTypes.ClientCredentials,                    // 加密驗證                    ClientSecrets = new List<Secret>                    {                        new Secret("secret".Sha256())                    },                    // client可以訪問的範圍,在上面定義的。                    AllowedScopes = new List<string>                    {                        "zeroapi"                    }                }            };          }

定義好以後,在Startup.cs 中 配置IdentityServer4

        public void ConfigureServices(IServiceCollection services)        {            services.AddDeveloperIdentityServer()                .AddInMemoryScopes(Config.GetScopes())                .AddInMemoryClients(Config.GetClients());        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            app.UseIdentityServer();        }

然後我們啟動IdentityServer4Demo 

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

IdentityServer 建立成功。

 

建立WebAPI項目

然後添加引用。

NuGet命令列:

Install-Package IdentityServer4.AccessTokenValidation -Pre

 

首先更改API 的URL地址,不和Server 重複。

這裡改為 http://localhost:5001

        public static void Main(string[] args)        {            var host = new WebHostBuilder()                .UseKestrel()                .UseUrls("http://localhost:5001")                .UseContentRoot(Directory.GetCurrentDirectory())                .UseIISIntegration()                .UseStartup<Startup>()                .Build();            host.Run();        }

然後在Startup.cs 中 配置相關資訊

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions            {                Authority = "http://localhost:5000",                ScopeName = "zeroapi",                RequireHttpsMetadata = false            });            app.UseMvc();        }

注意:這裡定義的授權地址是  http://localhost:5000 

下面我們來定義API,添加一個Web API 控制器 ClientController 

    [Route("api/[controller]")]    [Authorize]    public class ClientController : Controller    {        [HttpGet]        public IActionResult Get()        {            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });        }    }

上面添加了 Authorize 特性,直接存取API 是無法訪問的。

程式啟動以後,訪問http://localhost:5001/api/client 會返回401 。

用戶端調用

建立一個用戶端調用,添加一個控制台程式 Client。

首先也要添加引用:

NuGet命令列:

Install-Package IdentityModel

用戶端代碼如下:

        public static void Main(string[] args)        {            //訪問授權伺服器擷取token            var disco = DiscoveryClient.GetAsync("http://localhost:5000").Result;            var tokenClient = new TokenClient(disco.TokenEndpoint, "linezeroclient", "secret");            var tokenResponse = tokenClient.RequestClientCredentialsAsync("zeroapi").Result;            if (tokenResponse.IsError)            {                Console.WriteLine(tokenResponse.Error);                return;            }            Console.WriteLine(tokenResponse.Json);            Console.WriteLine("==============================");            //設定token 訪問API            var client = new HttpClient();            client.SetBearerToken(tokenResponse.AccessToken);            var response = client.GetAsync("http://localhost:5001/api/client").Result;            if (!response.IsSuccessStatusCode)            {                Console.WriteLine(response.StatusCode);            }            var content = response.Content.ReadAsStringAsync().Result;            Console.WriteLine(content);            Console.ReadKey();        }

 

然後開始一個個運行。

首先啟動 IdentityServer4Demo,然後API 然後Client。

Client 成功訪問 API 。使用用戶端憑據保護API 到這裡就基本完成。

更多IdentityServer4資訊:https://identityserver4.readthedocs.io/

 

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0架構學習保護API

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.