Server/Node.js

NodeJS - 권한 제어 (Endpoint별 인증, 인가) 하는 법! (+ middleware)

JaeHoney 2022. 2. 13. 15:15

NodeJS 인증, 인가

특정 엔드포인트마다 뭔가를 검증해야 하는 서비스가 있습니다! 예를 들어서, 관리자만 사용할 수 있는 API가 있다거나 하는 경우가 있죠!

 

그럴 경우에 해당 컨트롤러 메서드에서, 검증을 해서 거를 수도 있습니다. 하지만, 그것보다는 훨씬 직관적인 방법이 있습니다! 바로 Middleware를 이용하는 방법입니다.

 

Middleware 작성

const authenticateAdmin = async (req:Request, res:Response, next:NextFunction) => {
    if(isSuperAdmin(req.jwt) || await isBookingAdmin(req.jwt)) {
        return next();
    } else{
        return next(new HttpException(HttpStatusCode.UNAUTHORIZED, "Unauthorized"));
    }
};

export {
    authenticateAdmin
};

function isSuperAdmin(jwt: JWT) {
    return jwt.user.level === "admin";
}

async function isBookingAdmin(jwt: JWT) {
    const object: Admin = await Admin.findOne({
        where: {
            officeId: jwt.user.officeId,
            userId: jwt.user.id
        }
    });
    return object !== null;
}

먼저, middleware를 작성합니다. 저의 경우 src/middlewares/Authentication.ts 라는 이름으로 작성했습니다.

 

authenticateAdmin은 request를 받아서 관리자 여부를 검사하고 권한이 적합하지 않으면 예외를 던지는 함수입니다.

 

컨트롤러 메서드에 부착

router.post("/change-order", authenticateAdmin, categoryController.updateOrders);

이제 특정 엔드포인트에 컨트롤러 메서드를 연결할 때 두 번째 파라미터에 작성한 authenticateAdmin변수를 import해서 사용하면 됩니다!

 

그러면, 특정 엔드포인트마다 원하는 로직을 삽입해서 예외처리를 낼 수 있고 아래처럼 관리자 API를 접근할 때는 반드시 권한 제어를 타게 만들 수도 있습니다!

router.use("/admin/categories", authenticateAdmin, CategoryManage);
router.use("/categories", Category);

 

 

감사합니다!