Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[43] AOP 를 사용한 권한 체크 #45

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.example.commerce_site.common.auth;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PartnerCheck {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package org.example.commerce_site.common.auth;

import java.util.List;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.commerce_site.attribute.UserRoles;
import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.example.commerce_site.common.util.JwtUtil;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Aspect
@RequiredArgsConstructor
@Component
public class RoleCheckAspect {

private static final String AUTHORIZATION = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
private final HttpServletRequest httpServletRequest;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 request는 어디서 받아오나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

클라이언트가 서버에 요청을 보내면 tomcat 이 이를 수신하고 디스패쳐 서블릿으로 보냅니다.
디스패쳐 서블릿은 모든 http 요청을 가로채서 요청이 처리 되는 동안에 유효한 HttpServletRequest 객체를 만들고 스프링에서 이를 주입해줍니다.

private final JwtUtil jwtUtil;

@Around("@annotation(org.example.commerce_site.common.auth.PartnerCheck)")
public Object checkPartner(ProceedingJoinPoint joinPoint) throws Throwable {
return checkRole(joinPoint, UserRoles.ROLE_PARTNER);
}

@Around("@annotation(org.example.commerce_site.common.auth.UserCheck)")
public Object checkUser(ProceedingJoinPoint joinPoint) throws Throwable {
return checkRole(joinPoint, UserRoles.ROLE_USER);
}

private Object checkRole(ProceedingJoinPoint joinPoint, UserRoles requiredRole) throws Throwable {
String token = extractTokenFromRequest();
Jwt jwt = jwtUtil.decodeToken(token);
List<String> roleList = extractAuthorities(jwt);

if (!roleList.contains(requiredRole.name())) {
throw new CustomException(ErrorCode.ACCESS_DENIED);
}

return joinPoint.proceed();
}

private String extractTokenFromRequest() {
String authorizationHeader = httpServletRequest.getHeader(AUTHORIZATION);
if (authorizationHeader == null || !authorizationHeader.startsWith(BEARER_PREFIX)) {
throw new CustomException(ErrorCode.ACCESS_DENIED);
}
return authorizationHeader.substring(BEARER_PREFIX.length());
}

private List<String> extractAuthorities(Jwt jwt) {
var resourceAccess = (Map<String, Object>)jwt.getClaim("resource_access");
var roles = (Map<String, Object>)resourceAccess.get("oauth2-client-app");
return (List<String>)roles.get("roles");
}
}
11 changes: 11 additions & 0 deletions src/main/java/org/example/commerce_site/common/auth/UserCheck.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.example.commerce_site.common.auth;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserCheck {
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public enum ErrorCode {
INVALID_PARAM(HttpStatus.BAD_REQUEST, 400, "잘못된 parameter 입니다."),
ACCESS_DENIED(HttpStatus.FORBIDDEN, 403, "권한이 부족합니다."),
METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, 405, "허용되지 않은 메소드 입니다."),
//auth
JWT_DECODING_ERROR(HttpStatus.UNAUTHORIZED, 401, "JWT Decoding error"),

//address
ADDRESS_NOT_FOUND(HttpStatus.NOT_FOUND, 404, "배송지 정보를 찾을 수 없습니다."),

Expand Down
27 changes: 27 additions & 0 deletions src/main/java/org/example/commerce_site/common/util/JwtUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.example.commerce_site.common.util;

import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtil {
private final NimbusJwtDecoder jwtDecoder;

public Jwt decodeToken(String token) {
try {
return jwtDecoder.decode(token);
} catch (JwtException e) {
log.error(e.getMessage());
throw new CustomException(ErrorCode.JWT_DECODING_ERROR);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.example.commerce_site.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

@Configuration
public class JwtDecoderConfig {
@Bean
public NimbusJwtDecoder jwtDecoder() {
String jwkSetUri = "http://localhost:9090/realms/oauth2/protocol/openid-connect/certs";
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
}
}
23 changes: 0 additions & 23 deletions src/main/java/org/example/commerce_site/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package org.example.commerce_site.config;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.example.commerce_site.config.filter.UserIdFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -15,10 +10,7 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
Expand Down Expand Up @@ -46,7 +38,6 @@ protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(this::extractAuthorities);

http
.csrf(AbstractHttpConfigurer::disable)
Expand All @@ -64,18 +55,4 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti

return http.build();
}

private Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
var resourceAccess = (Map<String, Object>)jwt.getClaim("resource_access");
var roles = (Map<String, Object>)resourceAccess.get("oauth2-client-app");

if (roles != null) {
var roleList = (List<String>)roles.get("roles");
return roleList.stream()
.map(role -> new SimpleGrantedAuthority(role))
.collect(Collectors.toList());
}

return List.of();
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.example.commerce_site.representation.address;

import org.example.commerce_site.application.address.AddressFacade;
import org.example.commerce_site.common.auth.UserCheck;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.address.dto.AddressRequest;
import org.example.commerce_site.representation.address.dto.AddressResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -26,7 +26,7 @@
public class AddressController {
private final AddressFacade addressFacade;

@PreAuthorize("hasAuthority('ROLE_USER')")
@UserCheck
@PostMapping()
public ApiSuccessResponse createAddrss(
@Valid @RequestBody AddressRequest.Create request,
Expand All @@ -35,7 +35,7 @@ public ApiSuccessResponse createAddrss(
return ApiSuccessResponse.success();
}

@PreAuthorize("hasAuthority('ROLE_USER')")
@UserCheck
@GetMapping("/{address_id}")
public ApiSuccessResponse<AddressResponse.Get> getAddress(
@RequestAttribute("userId") String userAuthId,
Expand All @@ -44,7 +44,7 @@ public ApiSuccessResponse<AddressResponse.Get> getAddress(
AddressResponse.Get.of(addressFacade.get(addressId, userAuthId)));
}

@PreAuthorize("hasAuthority('ROLE_USER')")
@UserCheck
@GetMapping()
public ApiSuccessResponse.PageList<AddressResponse.Get> getAddresses(
@RequestAttribute("userId") String userAuthId,
Expand All @@ -53,7 +53,7 @@ public ApiSuccessResponse.PageList<AddressResponse.Get> getAddresses(
return ApiSuccessResponse.success(AddressResponse.Get.of(addressFacade.getList(userAuthId, page - 1, size)));
}

@PreAuthorize("hasAuthority('ROLE_USER')")
@UserCheck
@DeleteMapping("/{address_id}")
public ApiSuccessResponse deleteAddress(
@RequestAttribute("userId") String userAuthId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.example.commerce_site.representation.cart;

import org.example.commerce_site.application.cart.CartFacade;
import org.example.commerce_site.common.auth.UserCheck;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.cart.dto.CartRequest;
import org.example.commerce_site.representation.cart.dto.CartResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
Expand All @@ -21,10 +21,10 @@
@RestController
@RequiredArgsConstructor
@RequestMapping("/carts")
@PreAuthorize("hasAuthority('ROLE_USER')")
public class CartController {
private final CartFacade cartFacade;

@UserCheck
@PostMapping()
public ApiSuccessResponse createCart(
@RequestAttribute("userId") String userAuthId,
Expand All @@ -33,6 +33,7 @@ public ApiSuccessResponse createCart(
return ApiSuccessResponse.success();
}

@UserCheck
@DeleteMapping()
public ApiSuccessResponse deleteCart(
@RequestAttribute("userId") String userAuthId,
Expand All @@ -41,6 +42,7 @@ public ApiSuccessResponse deleteCart(
return ApiSuccessResponse.success();
}

@UserCheck
@PatchMapping()
public ApiSuccessResponse updateCart(
@RequestAttribute("userId") String userAuthId,
Expand All @@ -50,6 +52,7 @@ public ApiSuccessResponse updateCart(
return ApiSuccessResponse.success();
}

@UserCheck
@GetMapping()
public ApiSuccessResponse.PageList<CartResponse.Get> getCart(
@RequestAttribute("userId") String userAuthId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package org.example.commerce_site.representation.order;

import org.example.commerce_site.application.order.OrderFacade;
import org.example.commerce_site.common.auth.UserCheck;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.order.request.OrderRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -18,6 +18,7 @@
public class OrderController {
private final OrderFacade orderFacade;

@UserCheck
@PostMapping()
public ApiSuccessResponse createOrder(
@RequestAttribute("userId") String userAuthId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package org.example.commerce_site.representation.payment;

import org.example.commerce_site.application.payment.PaymentFacade;
import org.example.commerce_site.common.auth.UserCheck;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.payment.dto.PaymentRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
Expand All @@ -18,10 +18,10 @@
@RestController
@RequiredArgsConstructor
@RequestMapping("/payments")
@PreAuthorize("hasAuthority('ROLE_USER')")
public class PaymentController {
private final PaymentFacade paymentFacade;

@UserCheck
@PostMapping("/{order_id}")
public ApiSuccessResponse createPayment(
@PathVariable("order_id") Long orderId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.example.commerce_site.representation.product;

import org.example.commerce_site.application.product.ProductFacade;
import org.example.commerce_site.common.auth.PartnerCheck;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.product.request.ProductRequest;
import org.example.commerce_site.representation.product.response.ProductResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
Expand All @@ -25,7 +25,7 @@
public class ProductController {
private final ProductFacade productFacade;

@PreAuthorize("hasAuthority('ROLE_PARTNER')")
@PartnerCheck
@PostMapping()
public ApiSuccessResponse createProduct(
@Valid @RequestBody ProductRequest.Create request,
Expand All @@ -34,7 +34,7 @@ public ApiSuccessResponse createProduct(
return ApiSuccessResponse.success();
}

@PreAuthorize("hasAuthority('ROLE_PARTNER')")
@PartnerCheck
@PatchMapping("/{product_id}")
public ApiSuccessResponse updateProduct(
@PathVariable(name = "product_id") Long productId,
Expand All @@ -45,7 +45,7 @@ public ApiSuccessResponse updateProduct(
return ApiSuccessResponse.success();
}

@PreAuthorize("hasAuthority('ROLE_PARTNER')")
@PartnerCheck
@DeleteMapping("/{product_id}")
public ApiSuccessResponse deleteProduct(
@PathVariable(name = "product_id") Long productId,
Expand Down
Loading