🐹.NET Core Disable Authentication in Development Environment

circle-info

หลังจากที่เราได้ลองสร้าง Web API ด้วย .NET Core และทำ Authentication ด้วย JWT กันไปแล้ว จะเห็นว่าในกรณีที่อยู่ใน Development Mode จะต้องทำการ Authentication ก่อนทุกครั้ง ทำให้เสียเวลา ซึ่งเราอาจเขียนให้ไม่ต้อง Authentication เมื่ออยู่ใน Development Mode

Get Started

  • ทำการสร้างไฟล์ DisableAuthorizationHandler.cs ในโฟลเดอร์ Services

DisableAuthorizationHandler.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace web_api.Services
{
    public class DisableAuthorizationHandler : AuthorizationHandler
    where TRequirement : IAuthorizationRequirement
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }
}
  • ทำการสร้างไฟล์ TransientExtension.cs ในโฟลเดอร์ Services

  • ทำการเรียกใช้คลาส ConfigureTransient ที่อยู่ในไฟล์ TransientExtension.cs เข้ามาในคลาส ConfigureServices ที่อยู่ในไฟล์ Startup.cs

  • คลิก Debug แล้วเลือก Start Debugging

อ่านเพิ่มเติม : https://bit.ly/37WnKNlarrow-up-right

Last updated