🐹.NET Core Disable Authentication in Development Environment

หลังจากที่เราได้ลองสร้าง 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://localhost:5001/index.html จะสามารถเรียกใช้ API โดยไม่ต้องทำการ Authentication ในโหมด Development

อ่านเพิ่มเติม : https://bit.ly/37WnKNl

Last updated

Was this helpful?