본문 바로가기

Programing/.NET Core

[.NET Core] 2. Web API MiddleWare 구성

이전글:

 

[.NET Core] 1. Web API 프로젝트 생성

1. 프로젝트생성 API 프로젝트 생성을 위해 ASP.NET Core 웹 응용 프로그램을 선택한다. 2.구성설정 Core 버전과 세부 프로젝트 구성을 설정할수있다. API 프로젝트 뿐만아니라 일반적인 웹응용프로그

tjddnjs625.tistory.com

 

 

해당 프로젝트는 API 프로젝트로 사용할 예정이기 때문에 MiddelWare 를 구성하여 API Key 값에 대한 유효성 검사를 진행한다.

 

APIKey 값을 appsettings.json 파일에 정의해두고 입력받은 헤더 값을 비교하여 결과를 리턴하기위해 먼저 위와 같이 폴더와 클래스 파일을 생성해주고 아래와 같은 코드를 작성한다

 

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApiKey": "DotNetCoreAPIStudy"
}

 

ApiKeyMiddleware.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ApiProject.Middlewares
{
    public class ApiKeyMiddleware
    {
        private readonly RequestDelegate _next;
        private const string APIKEYNAME = "ApiKey";

        public ApiKeyMiddleware(RequestDelegate next)
        {
            _next = next;
        }

             public async Task InvokeAsync(HttpContext context)
        {
            //입력받은 Headers  'APIKEYNAME' 값을 조회후 값이없다면 401 에러 반환
            if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Api key was not provided");
                return;
            }

            //appsettings.json 에서 'APIKEYNAME' 값을 가져와 비교
            var appSetting = context.RequestServices.GetRequiredService<IConfiguration>();

            var apiKey = appSetting.GetValue<string>(APIKEYNAME);

            if (!apiKey.Equals(extractedApiKey))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Api key is not valid");
                return;
            }

            await _next(context);
    }
}

 

이제 작성한 Middleware 코드를 요청이 들어왔을때 실행하기위해 Startup.cs  Configure부분에 아래와같이추가해준다.

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            //ApiKeyMiddleware 추가
            app.UseMiddleware<ApiKeyMiddleware>();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

 

 

결과:

ApiKey 값 유효성검사 실패시 status : 401 반환

성공 status 200 반환

 

위와같이 appsettings.json 에 Key를정의할수도 있고 DB에서 값을 조회해서 비교할수도 있다.

 

'Programing > .NET Core' 카테고리의 다른 글

[.NET Core] 3. Web API DB 연결 (Dapper)  (0) 2022.09.15
[.NET Core] 1. Web API 프로젝트 생성  (0) 2022.09.15