.Net Core 創建webApi,Token以及 IdentityServer4


參考地址

VsCode

1.創建WebApi

創建 webApi項目

dotnet new weiapi

2.安裝 identityserver4 包,目的是為了獲取token

dotnet add package IdentityServer4

3.安裝 IdentityServer4.AccessTokenValidation 包,目的是為了權限驗證

dotnet add package IdentityServer4.AccessTokenValidation

3.配置一個 IdentityServerConfig.cs 文件 (這邊配置放在根目錄下面)。目的是為了在startup.cs引用

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

namespace IdentityServer4Test.IndntityConfig
{
    public class IdentityServerConfig
    {
        /// <summary>
        /// 添加api資源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource>
            {
          
                new ApiResource("api1","My Api")
            };
        }
        /// <summary>
        /// 添加客戶端,定義一個可以訪問此api的客戶端
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
                {
                    new Client
                    {
                        ///
                        ClientId = "client",

                        // 沒有交互性用戶,使用 客戶端模式 進行身份驗證。
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                       
                        // 用於認證的密碼
                        ClientSecrets =
                        {
                            new Secret("1234554".Sha256())
                        },
                        // 客戶端有權訪問的范圍(Scopes)
                        AllowedScopes = { "api1" }
                    }
 
                };

        }
    }
}

4.Startup.cs 修改

  1. ConfigureServices方法里面 修改為如下
       services.AddControllers();

            services.AddIdentityServer()
            .AddInMemoryApiResources(IdentityServerConfig.GetResources())//添加配置的api資源
            .AddInMemoryClients(IdentityServerConfig.GetClients())//添加客戶端,定義一個可以訪問此api的客戶端
            .AddDeveloperSigningCredential();

            services.AddAuthentication("Bearer")
       .AddJwtBearer("Bearer", options =>
       {
           options.Authority = "http://localhost:5000/"; //權限驗證url
           options.RequireHttpsMetadata = false;//是否開啟https
           options.Audience = "api1";
       });

2.Configure方法 修改為如下

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();//開啟Token  配置ASP.NET Core管道
                                    //  //添加authentication中間件到http管道
            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

5.PostMan測試

post測試,使用http好一點,https在權限認證報錯
https地址:https://localhost:5001/connect/token
http地址:http://localhost:5000/connect/token  

form-data參數:
grant_type:client_credentials
client_id:client
client_secret:1234554


請求后會獲取到如下大致內容:
{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ill2VmdnbDFUamppQWpFS1VmR2NZYlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODUwMzk0NDUsImV4cCI6MTU4NTA0MzA0NSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NTAwMSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiJjbGllbnQiLCJzY29wZSI6WyJhcGkxIl19.jV10uH5uo2Ubd2eaqbN521utFc8N7zevgm46tQ9Ka9lIeC-hqOx10bI1BZbWwQjxHla6RAkqwJ0QlyaCZTUk3BVnbFmwnRdW3e08fwSLVY7s2fFuKPJC0bCh3ggLGyoMZgX5cIgpyvyRvI_DIq6vI-6Gpv0aVsPiAfFh5-zLHNfgc5qJ8soG4iP5E33n-SdglICUWuosA2TuF2V7sJaES363emQqa0QnLZQQNgztjlJc2tZViUjOvHa1lk8US_FaHQ6lG6CIRrutQaMnYKSrCcXUBfkAY1b3gnNJ-j_OxeatxuFX7l2uzzKIMEhB2IGg4oej6YYbsCheeOW1ZBoRRw",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "api1"
}

6.權限測試。 API控制器增加 [Authorize]。首先需要安裝 IdentityServer4.AccessTokenValidation 。

API控制器

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

[Route("identity/[action]")]
public class IdentityController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public string Get()
    {
        return "有權限get成功";
    }

      [HttpGet]
    public string Get2()
    {
        return "無權限get成功";
    }
}

采用postman請求測試。不帶token請求get直接報錯401。
權限測試地址

VS studio

跟着這個做大致一樣


免責聲明!

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



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