첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
------------------------------------------------------------------------------------------------------------------------------------------------------
728x90
728x170

TestSolution.zip
다운로드

[TestIdentityServer 프로젝트]

▶ Properties/launchSettings.json

{
    "iisSettings" :
    {
        "windowsAuthentication"   : false, 
        "anonymousAuthentication" : true, 
        "iisExpress"              :
        {
            "applicationUrl" : "http://localhost:50000",
            "sslPort"        : 44300
        }
    },
    "profiles" :
    {
        "IIS Express" :
        {
            "commandName"          : "IISExpress",
            "launchBrowser"        : true,
            "environmentVariables" :
            {
                "ASPNETCORE_ENVIRONMENT" : "Development"
            }
        },
        "TestIdentityServer" :
        {
            "commandName"          : "Project",
            "launchBrowser"        : true,
            "applicationUrl"       : "https://localhost:5001;http://localhost:5000",
            "environmentVariables" :
            {
                "ASPNETCORE_ENVIRONMENT" : "Development"
            }
        }
    }
}

 

728x90

 

▶ Configuration.cs

using System.Collections.Generic;

using IdentityServer4.Models;

namespace TestIdentityServer
{
    /// <summary>
    /// 구성
    /// </summary>
    public static class Configuration
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region API 범위 리스트 구하기 - GetAPIScopeList

        /// <summary>
        /// API 범위 리스트 구하기
        /// </summary>
        public static List<ApiScope> GetAPIScopeList()
        {
            return new List<ApiScope>
            {
                new ApiScope("API1", "API 1")
            };
        }

        #endregion
        #region 클라이언트 리스트 구하기 - GetClientList()

        /// <summary>
        /// 클라이언트 리스트 구하기
        /// </summary>
        /// <returns></returns>
        public static List<Client> GetClientList()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId          = "CLIENTID0001",
                    ClientSecrets     = { new Secret("CLIENTSECRET0001".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowedScopes     = { "API1" }
                }
            };
        }

        #endregion
    }
}

 

300x250

 

▶ Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TestIdentityServer
{
    /// <summary>
    /// 시작
    /// </summary>
    public class Startup
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 서비스 컬렉션 구성하기 - ConfigureServices(services)

        /// <summary>
        /// 서비스 컬렉션 구성하기
        /// </summary>
        /// <param name="services">서비스 컬렉션</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiScopes(Configuration.GetAPIScopeList())
                .AddInMemoryClients(Configuration.GetClientList());

            services.AddControllersWithViews();
        }

        #endregion
        #region 구성하기 - Configure(app, environment)

        /// <summary>
        /// 구성하기
        /// </summary>
        /// <param name="app">애플리케이션 빌더</param>
        /// <param name="environment">웹 호스트 환경</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
        {
            if(environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseIdentityServer();

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

        #endregion
    }
}

 

[TestAPIServer 프로젝트]

▶ Properties/launchSettings.json

{
    "iisSettings" :
    {
        "windowsAuthentication"   : false, 
        "anonymousAuthentication" : true, 
        "iisExpress"              :
        {
            "applicationUrl" : "http://localhost:50010",
            "sslPort"        : 44310
        }
    },
    "profiles" :
    {
        "IIS Express" :
        {
            "commandName"          : "IISExpress",
            "launchBrowser"        : true,
            "environmentVariables" :
            {
                "ASPNETCORE_ENVIRONMENT" : "Development"
            }
        },
        "TestIdentityServer" :
        {
            "commandName"          : "Project",
            "launchBrowser"        : true,
            "applicationUrl"       : "https://localhost:5001;http://localhost:5000",
            "environmentVariables" :
            {
                "ASPNETCORE_ENVIRONMENT" : "Development"
            }
        }
    }
}

 

▶ Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;

namespace TestAPIServer
{
    /// <summary>
    /// 시작
    /// </summary>
    public class Startup
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 서비스 컬렉션 구성하기 - ConfigureServices(services)

        /// <summary>
        /// 서비스 컬렉션 구성하기
        /// </summary>
        /// <param name="services">서비스 컬렉션</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddJwtBearer
                (
                    "Bearer",
                    options =>
                    {
                        options.Authority = "https://localhost:44300";

                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateAudience = false
                        };
                    }
                );

            services.AddAuthorization
            (
                options =>
                {
                    options.AddPolicy
                    (
                        "APIScope",
                        policy =>
                        {
                            policy.RequireAuthenticatedUser();
                            policy.RequireClaim("scope", "API1");
                        }
                    );
                }
            );

            services.AddControllersWithViews();
        }

        #endregion
        #region 구성하기 - Configure(app, environment)

        /// <summary>
        /// 구성하기
        /// </summary>
        /// <param name="app">애플리케이션 빌더</param>
        /// <param name="environment">웹 호스트 환경</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
        {
            if(environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

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

        #endregion
    }
}

 

▶ Controllers/IdentityController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace TestAPIServer.Controllers
{
    /// <summary>
    /// 신원 컨트롤러
    /// </summary>
    public class IdentityController : Controller
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 인덱스 페이지 처리하기 - Index()

        /// <summary>
        /// 인덱스 페이지 처리하기
        /// </summary>
        /// <returns>액션 결과</returns>
        [HttpGet]
        [Authorize("APIScope")]
        public IActionResult Index()
        {
            return new JsonResult(from claim in User.Claims select new { claim.Type, claim.Value });
        }

        #endregion
    }
}

 

[TestConsole 프로젝트]

▶ Program.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;

using Newtonsoft.Json.Linq;

using IdentityModel.Client;

namespace TestClient
{
    /// <summary>
    /// 프로그램
    /// </summary>
    public class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        /// <returns>태스크</returns>
        private static async Task Main()
        {
            HttpClient identityClient = new HttpClient();

            DiscoveryDocumentResponse discoveryDocumentResponse = await identityClient.GetDiscoveryDocumentAsync("https://localhost:44300");

            if(discoveryDocumentResponse.IsError)
            {
                Console.WriteLine(discoveryDocumentResponse.Error);

                return;
            }

            TokenResponse tokenResponse = await identityClient.RequestClientCredentialsTokenAsync
            (
                new ClientCredentialsTokenRequest
                {
                    Address      = discoveryDocumentResponse.TokenEndpoint,
                    ClientId     = "CLIENTID0001",
                    ClientSecret = "CLIENTSECRET0001",
                    Scope        = "API1"
                }
            );
            
            if(tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);

                return;
            }

            Console.WriteLine("TOKEN RESPONSE");
            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("--------------------------------------------------");

            HttpClient apiClient = new HttpClient();

            apiClient.SetBearerToken(tokenResponse.AccessToken);

            HttpResponseMessage apiResponse = await apiClient.GetAsync("https://localhost:44310/identity/index");

            if(!apiResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(apiResponse.StatusCode);
            }
            else
            {
                string content = await apiResponse.Content.ReadAsStringAsync();

                Console.WriteLine("API RESPONSE");
                Console.WriteLine("--------------------------------------------------");
                Console.WriteLine(JArray.Parse(content));
                Console.WriteLine("--------------------------------------------------");
            }
        }

        #endregion
    }
}
728x90
그리드형(광고전용)
Posted by icodebroker
,