[C#/ASP.NET MVC/.NETCORE] IdentityServer4 클라이언트 자격 증명을 사용하여 API 보호하기
C#/ASP.NET MVC 2020. 11. 3. 20:55728x90
728x170
[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
그리드형(광고전용)
'C# > ASP.NET MVC' 카테고리의 다른 글
[C#/ASP.NET MVC/.NETCORE] 누겟 설치 : Microsoft.AspNetCore.Authentication.OpenIdConnect (0) | 2020.11.05 |
---|---|
[C#/ASP.NET MVC/.NETCORE] 누겟 설치 : IdentityServer4.AspNetIdentity (0) | 2020.11.05 |
[C#/ASP.NET MVC/.NETCORE] 누겟 설치 : IdentityServer4 (0) | 2020.11.05 |
[C#/ASP.NET MVC/.NETCORE] IdentityServer4 신원 서버에서 사용자 인증하고 API 호출하기 (0) | 2020.11.04 |
[C#/ASP.NET MVC/.NETCORE] IdentityServer4 신원 서버에서 사용자 로그인 인증하기 (0) | 2020.11.04 |
[C#/ASP.NET MVC/.NETCORE] RazorPageBase 클래스 : User 속성 사용하기 (0) | 2020.11.03 |
[C#/ASP.NET MVC/.NETCORE] dotnet run 명령 : 환경 변수를 설정하고 프로그램 실행하기 (0) | 2020.11.03 |
[C#/ASP.NET MVC/.NETCORE] dotnet new -i 명령 : IdentityServer4 템플리트 설치하기 (0) | 2020.11.03 |
[C#/ASP.NET MVC/.NETCORE] IdentityServer4 인증 사용하기 (개념 학습용) (0) | 2020.11.03 |
[C#/ASP.NET MVC/.NETCORE] AREA 사용하기 (0) | 2020.11.03 |