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

TestSolution.zip
다운로드

▶ APIService.cs

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

using IdentityModel.Client;

namespace TestClient
{
    /// <summary>
    /// API 서비스
    /// </summary>
    public class APIService
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region HTTP 클라이언트 - Client

        /// <summary>
        /// HTTP 클라이언트
        /// </summary>
        public HttpClient Client { get; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - APIService(client)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="client">HTTP 클라이언트</param>
        public APIService(HttpClient client)
        {
            client.BaseAddress = new Uri("https://localhost:44310/");

            client.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");

            Client = client;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 비밀 구하기 - GetSecret(accessToken)

        /// <summary>
        /// 비밀 구하기
        /// </summary>
        /// <param name="accessToken">액세스 토큰</param>
        /// <returns>문자열 태스크</returns>
        public async Task<string> GetSecret(string accessToken)
        {
            Client.SetBearerToken(accessToken);

            var response = await Client.GetAsync("secret");

            response.EnsureSuccessStatusCode();

            HttpResponseMessage apiResponse = await Client.GetAsync("https://localhost:44310/secret");

            string content = await apiResponse.Content.ReadAsStringAsync();

            return content;
        }

        #endregion
    }
}

 

728x90

 

▶ Startup.cs

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"   );
                }
            );

            services.AddHttpClient<APIService>();

            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
    }
}

 

300x250

 

▶ Controllers/HomeController.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Threading.Tasks;

namespace TestClient.Controllers
{
    /// <summary>
    /// 홈 컨트롤러
    /// </summary>
    public class HomeController : Controller
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// API 서비스
        /// </summary>
        private readonly APIService service;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - HomeController(service)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="service">API 서비스</param>
        public HomeController(APIService service)
        {
            this.service = service;
        }

        #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");

            JwtSecurityToken accessJwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);

            string secret = await this.service.GetSecret(accessToken);

            ViewData["Secret"] = secret;

            return View();
        }

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