■ IdentityServer4 액세스 토큰을 갱신하는 방법을 보여준다.
[TestIdentityServer 프로젝트]
▶ Properties/launchSetting.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{ "iisSettings" : { "windowsAuthentication" : false, "anonymousAuthentication" : true, "iisExpress" : { "applicationUrl" : "http://localhost:50000", "sslPort" : 44300 } }, "profiles" : { "IIS Express" : { "commandName" : "IISExpress", "launchBrowser" : true, "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } }, "TestAuthorizationServer" : { "commandName" : "Project", "launchBrowser" : true, "applicationUrl" : "https://localhost:5001;http://localhost:5000", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } } } } |
▶ Configuration.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System.Collections.Generic; using IdentityModel; using IdentityServer4; using IdentityServer4.Models; namespace TestIdentityServer { /// <summary> /// 구성 /// </summary> public static class Configuration { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 신원 리소스 리스트 구하기 - GetIdentityResourceList() /// <summary> /// 신원 리소스 리스트 구하기 /// </summary> /// <returns>신원 리소스 리스트</returns> public static List<IdentityResource> GetIdentityResourceList() { return new List<IdentityResource>() { new IdentityResources.OpenId(), new IdentityResources.Profile() }; } #endregion #region API 범위 리스트 구하기 - GetAPIScopeList() /// <summary> /// API 범위 리스트 구하기 /// </summary> /// <returns>API 범위 리스트</returns> public static List<ApiScope> GetAPIScopeList() { return new List<ApiScope> { new ApiScope("API1", "API 1"), new ApiScope("API2", "API 2") }; } #endregion #region 클라이언트 리스트 구하기 - GetClientList() /// <summary> /// 클라이언트 리스트 구하기 /// </summary> /// <returns>클라이언트 리스트</returns> public static List<Client> GetClientList() { return new List<Client> { new Client { AllowedGrantTypes = GrantTypes.ClientCredentials, ClientId = "CLIENTID0002", ClientSecrets = { new Secret("CLIENTSECRET0002".ToSha256()) }, AllowedScopes = new List<string> { "API1" } }, new Client { AllowedGrantTypes = GrantTypes.Code, ClientId = "CLIENTID0003", ClientSecrets = { new Secret("CLIENTSECRET0003".ToSha256()) }, RedirectUris = { "https://localhost:44330/signin-oidc" }, AllowedScopes = new List<string> { "API1", "API2", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile }, RequireConsent = false, AllowOfflineAccess = true } }; } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestIdentityServer.Data; namespace TestIdentityServer { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DatabaseContext>(options => { options.UseInMemoryDatabase("MemoryDB"); }); services.AddIdentity<IdentityUser, IdentityRole> ( options => { options.Password.RequiredLength = 4; options.Password.RequireDigit = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; } ) .AddEntityFrameworkStores<DatabaseContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie ( options => { options.Cookie.Name = "IdentityServer.Cookie"; options.LoginPath = "/Auth/Login"; } ); services.AddIdentityServer() .AddAspNetIdentity<IdentityUser>() .AddInMemoryIdentityResources(Configuration.GetIdentityResourceList()) .AddInMemoryApiScopes(Configuration.GetAPIScopeList()) .AddInMemoryClients(Configuration.GetClientList()) .AddDeveloperSigningCredential(); 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 } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TestIdentityServer { /// <summary> /// 프로그램 /// </summary> public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 프로그램 시작하기 - Main(argumentArray) /// <summary> /// 프로그램 시작하기 /// </summary> /// <param name="argumentArray">인자 배열</param> public static void Main(string[] argumentArray) { IHost host = CreateHostBuilder(argumentArray).Build(); using(IServiceScope scope = host.Services.CreateScope()) { UserManager<IdentityUser> userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>(); IdentityUser user = new IdentityUser("alice"); userManager.CreateAsync(user, "alice").GetAwaiter(); } host.Run(); } #endregion #region 호스트 빌더 생성하기 - CreateHostBuilder(argumentArray) /// <summary> /// 호스트 빌더 생성하기 /// </summary> /// <param name="argumentArray">인자 배열</param> /// <returns>호스트 빌더</returns> public static IHostBuilder CreateHostBuilder(string[] argumentArray) => Host.CreateDefaultBuilder(argumentArray) .ConfigureWebHostDefaults ( builder => { builder.UseStartup<Startup>(); } ); #endregion } } |
[TestAPIServer1 프로젝트]
▶ Properties/launchSettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{ "iisSettings" : { "windowsAuthentication" : false, "anonymousAuthentication" : true, "iisExpress" : { "applicationUrl" : "http://localhost:50010", "sslPort" : 44310 } }, "profiles" : { "IIS Express" : { "commandName" : "IISExpress", "launchBrowser" : true, "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } }, "TestAuthorizationServer" : { "commandName" : "Project", "launchBrowser" : true, "applicationUrl" : "https://localhost:5001;http://localhost:5000", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } } } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; namespace TestAPIServer1 { /// <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/SecretController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace TestAPIServer1.Controllers { /// <summary> /// 비밀 컨트롤러 /// </summary> public class SecretController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>문자열</returns> [Authorize("APIScope")] public string Index() { return "API 서버 1 비밀 메시지"; } #endregion } } |
[TestClient 프로젝트]
▶ Properties/launchSettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{ "iisSettings" : { "windowsAuthentication" : false, "anonymousAuthentication" : true, "iisExpress" : { "applicationUrl" : "http://localhost:50030", "sslPort" : 44330 } }, "profiles" : { "IIS Express" : { "commandName" : "IISExpress", "launchBrowser" : true, "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } }, "TestAuthorizationServer" : { "commandName" : "Project", "launchBrowser" : true, "applicationUrl" : "https://localhost:5001;http://localhost:5000", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } } } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TestClient { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddAuthentication ( options => { options.DefaultScheme = "Cookie"; options.DefaultChallengeScheme = "oidc"; } ) .AddCookie("Cookie") .AddOpenIdConnect ( "oidc", options => { options.Authority = "https://localhost:44300/"; options.ClientId = "CLIENTID0003"; options.ClientSecret = "CLIENTSECRET0003"; options.SaveTokens = true; options.ResponseType = "code"; options.Scope.Add("openid" ); options.Scope.Add("profile" ); options.Scope.Add("API1" ); options.Scope.Add("offline_access"); } ); services.AddHttpClient(); 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/HomeController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Net.Http; using System.Threading.Tasks; using IdentityModel.Client; namespace TestClient.Controllers { /// <summary> /// 홈 컨트롤러 /// </summary> public class HomeController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// HTTP 클라이언트 팩토리 /// </summary> private readonly IHttpClientFactory factory; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - HomeController(factory) /// <summary> /// 생성자 /// </summary> /// <param name="factory">HTTP 클라이언트 팩토리</param> public HomeController(IHttpClientFactory factory) { this.factory = factory; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Index() { return View(); } #endregion #region 비밀 페이지 처리하기 - Secret() /// <summary> /// 비밀 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [Authorize] public async Task<IActionResult> Secret() { string accessToken = await HttpContext.GetTokenAsync("access_token"); string secret = await GetSecret(accessToken); // 액세스 토큰이 갱신되는 것을 보여주는 테스트 코드이다. await RefreshAccessToken(); ViewData["Secret"] = secret; return View(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 비밀 구하기 - GetSecret(accessToken) /// <summary> /// 비밀 구하기 /// </summary> /// <param name="accessToken">액세스 토큰</param> /// <returns>비밀</returns> public async Task<string> GetSecret(string accessToken) { HttpClient apiClient = this.factory.CreateClient(); apiClient.SetBearerToken(accessToken); HttpResponseMessage apiResponse = await apiClient.GetAsync("https://localhost:44310/secret"); string content = await apiResponse.Content.ReadAsStringAsync(); return content; } #endregion #region 액세스 토큰 갱신하기 - RefreshAccessToken() /// <summary> /// 액세스 토큰 갱신하기 /// </summary> /// <returns>태스크</returns> private async Task RefreshAccessToken() { HttpClient discoveryClient = this.factory.CreateClient(); DiscoveryDocumentResponse discoveryDocumentResponse = await discoveryClient.GetDiscoveryDocumentAsync ( "https://localhost:44300/" ); string refreshToken = await HttpContext.GetTokenAsync("refresh_token"); HttpClient refreshTokenClient = this.factory.CreateClient(); TokenResponse tokenResponse = await refreshTokenClient.RequestRefreshTokenAsync ( new RefreshTokenRequest { Address = discoveryDocumentResponse.TokenEndpoint, RefreshToken = refreshToken, ClientId = "client_id_mvc", ClientSecret = "client_secret_mvc" } ); AuthenticateResult authenticateResult = await HttpContext.AuthenticateAsync("Cookie"); authenticateResult.Properties.UpdateTokenValue("id_token" , tokenResponse.IdentityToken); authenticateResult.Properties.UpdateTokenValue("access_token" , tokenResponse.AccessToken ); authenticateResult.Properties.UpdateTokenValue("refresh_token", tokenResponse.RefreshToken ); await HttpContext.SignInAsync("Cookie", authenticateResult.Principal, authenticateResult.Properties); } #endregion } } |
▶ Views/Home/Secret.cshtml
1 2 3 4 5 |
<h1>클라이언트 홈 비밀 페이지</h1> <hr /> <p>비밀 : @ViewData["Secret"]</p> |