logo MSJO.kr

ASP.NET Core WebAPI Basic Auth

2020-06-17
MsJ
   

이번에 살펴볼 소스 코드는 ASP.NET Core 프레임워크에서 Web API를 만들고 서비스할 때 사용자 인증 중 하나인 Basic Authentication을 설정하는 코드이다. 개발환경은 Visual Studio 2019에서 .NET Core 3.1을 기본 프레임워크로 설정하였다. 프로젝트 생성은 VS2019에서 ‘새 프로젝트 구성 → ASP.NET Core 웹 애플리케이션 → 프로젝트 이름 입력 → Empty(비어있음) 프로젝트‘를 생성한다. 테스트한 클라이언트 툴은 Postman을 사용하였고 Authorization Type은 Basic Auth(Username, Password)를 선택하였다.

Startup.cs
using BasicAuthCoreAPI.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace BasicAuthCoreAPI
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

            // 컨트롤러 [Route("api/xxx")] 일 때 Basic Auth
            app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", System.StringComparison.OrdinalIgnoreCase)),
                m => { m.UseMiddleware<AuthMiddleware>(); });

            app.UseRouting();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
DemoController.cs
using Microsoft.AspNetCore.Mvc;

namespace BasicAuthCoreAPI.Controllers
{
    [ApiController]
    public class DemoController : ControllerBase
    {
        [Route("demo1")]
        public IActionResult Demo1()
        {
            try
            {
                return Ok("Access Anyone");
            }
            catch (System.Exception)
            {
                return BadRequest();
            }
        }

        [Route("api/demo2")]
        public IActionResult Demo2()
        {
            try
            {
                return new ContentResult()
                {
                    ContentType = "text/html",
                    Content = "<b><i>Authorized User Access</i></b>"
                };
            }
            catch (System.Exception)
            {
                return BadRequest();
            }
        }
    }
}
AuthMiddleware.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Text;
using System.Threading.Tasks;

namespace BasicAuthCoreAPI.Middleware
{
    public class AuthMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task Invoke(HttpContext httpContext)
        {
            string authHeader = httpContext.Request.Headers["Authorization"];
            if (authHeader != null && authHeader.StartsWith("Basic"))
            {
                string authUserNameAndPassword = authHeader.Substring("Basic".Length).Trim();
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                string userNameAndPassword = encoding.GetString(Convert.FromBase64String(authUserNameAndPassword));
                int index = userNameAndPassword.IndexOf(":");
                var userName = userNameAndPassword.Substring(0, index);
                var password = userNameAndPassword.Substring(index + 1);

                // Basic Auth Username, Password설정
                if (userName.Equals("abc") && password.Equals("123"))
                {
                    await _next.Invoke(httpContext);
                }
                else
                {
                    await httpContext.Response.WriteAsync("Invalid Username or Password");
                    return;
                }
            }
            else
            {
                await httpContext.Response.WriteAsync("UserName and Password Authentication for WEB API");
                return;
            }
        }
    }

    public static class AuthMiddlewareExtensions
    {
        public static IApplicationBuilder UseAuthMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AuthMiddleware>();
        }
    }
}
추천 강좌
Reference

Prεv   Nεxt
Content
Search     RSS Feed     BY-NC-ND