Skip to content

Commit

Permalink
Fix: Spring Serurity 수정(권한설정 & 세션관리기능 수정)
Browse files Browse the repository at this point in the history
  • Loading branch information
suminiee authored Apr 2, 2024
2 parents 11878b1 + 3f26263 commit 86052dc
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.medicare.neulpeum.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class CustomAccessDenyHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
ErrorResponse errorResponse = new ErrorResponse(ErrorCode.FORBIDDEN_CLIENT);
ObjectMapper objectMapper = new ObjectMapper();
String jsonErrorResponse = objectMapper.writeValueAsString(errorResponse);

response.setStatus(HttpStatus.FORBIDDEN.value());
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE); // application/json
response.getWriter().write(jsonErrorResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.medicare.neulpeum.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
ErrorResponse errorResponse = new ErrorResponse(ErrorCode.UNAUTHORIZED_CLIENT);
ObjectMapper objectMapper = new ObjectMapper();
String jsonErrorResponse = objectMapper.writeValueAsString(errorResponse);

response.setStatus(HttpStatus.BAD_REQUEST.value());
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE); // application/json
response.getWriter().write(jsonErrorResponse);
}
}
22 changes: 22 additions & 0 deletions src/main/java/com/medicare/neulpeum/config/ErrorCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.medicare.neulpeum.config;

import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
public enum ErrorCode {
UNAUTHORIZED_CLIENT(HttpStatus.BAD_REQUEST, "접근 토큰이 없습니다."),
FORBIDDEN_CLIENT(HttpStatus.FORBIDDEN, "접근 권한이 없습니다."),
EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 토큰입니다."),
JWT_DECODE_FAIL(HttpStatus.UNAUTHORIZED, "올바른 토큰이 필요합니다."),
JWT_SIGNATURE_FAIL(HttpStatus.UNAUTHORIZED, "올바른 토큰이 필요합니다.");

private HttpStatus httpStatus;
private String message;


ErrorCode(HttpStatus httpStatus, String message) {
this.httpStatus = httpStatus;
this.message = message;
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/medicare/neulpeum/config/ErrorResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.medicare.neulpeum.config;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class ErrorResponse {
private String errorCode;
private String message;

public ErrorResponse(ErrorCode errorCode) {
this.errorCode = errorCode.name();
this.message = errorCode.getMessage();
}
}
18 changes: 16 additions & 2 deletions src/main/java/com/medicare/neulpeum/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
Expand All @@ -33,9 +34,15 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// 그 외 모든 요청 (any) 에 대해서는 인증 요구
.authorizeHttpRequests((authorizeRequest) ->
authorizeRequest
.requestMatchers("/api/login", "/api/**").permitAll()
.requestMatchers("/api/login").permitAll()
.requestMatchers("/accountSettings", "/drugs").hasAuthority("ADMIN")
.requestMatchers("/api/admin/**", "/api/drug").hasAuthority("ADMIN")
.anyRequest().authenticated()
)
.exceptionHandling(e -> e
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())//인증예외
.accessDeniedHandler(new CustomAccessDenyHandler())//인가예외
)

// Rest 방식으로 로그인을 할 것이므로 form 로그인 사용 안함
.formLogin(AbstractHttpConfigurer::disable)
Expand All @@ -50,7 +57,14 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//인증되지 않은 자원에 접근했을 때
.exceptionHandling((configurer) ->
configurer
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.FORBIDDEN)));
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.FORBIDDEN)))
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)//스프링 시큐리티가 항상 세션 생성
.invalidSessionUrl("/")//세션이 유효하지 않을 때 이동
.maximumSessions(-1)//최대 허용 가능 세션 수 : 무제한으로 설정
.expiredUrl("/")//세션 만료될 경우 페이지 이동
);


return http.build();
Expand Down

0 comments on commit 86052dc

Please sign in to comment.