Skip to content

Commit

Permalink
style: 코드 재정렬
Browse files Browse the repository at this point in the history
  • Loading branch information
kimday0326 committed Jun 6, 2024
1 parent 0f2936f commit c674437
Show file tree
Hide file tree
Showing 66 changed files with 1,788 additions and 1,941 deletions.
6 changes: 3 additions & 3 deletions src/main/java/com/khu/gitbox/GitboxApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
@EnableJpaAuditing
@SpringBootApplication
public class GitboxApplication {
public static void main(String[] args) {
SpringApplication.run(GitboxApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(GitboxApplication.class, args);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public AuthResponse login(LoginRequest request) {
request.email(),
request.password()
);

// 인증 및 Authentication 객체 생성
Authentication authenticated = authenticationManager.authenticate(authentication);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public UserDetails loadUserByUsername(String email) throws UsernameNotFoundExcep
return new UsernameNotFoundException("MEMBER_NOT_FOUND");
});


List<GrantedAuthority> authorities = getAuthorities(member);

return UserDetailsImpl.builder()
Expand Down
43 changes: 21 additions & 22 deletions src/main/java/com/khu/gitbox/auth/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
package com.khu.gitbox.auth.config;

import java.util.Arrays;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
log.info("CORS 설정 적용");
registry.addMapping("/**")
.allowedOrigins(getAllowOrigins())
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowCredentials(true);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
log.info("CORS 설정 적용");
registry.addMapping("/**")
.allowedOrigins(getAllowOrigins())
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowCredentials(true);
}

private String[] getAllowOrigins() {
return Arrays.asList(
"http://localhost",
"http://localhost:3000",
"http://localhost:1234",
"http://localhost:5173",
"http://125.250.17.196:1234"
).toArray(String[]::new);
}
private String[] getAllowOrigins() {
return Arrays.asList(
"http://localhost",
"http://localhost:3000",
"http://localhost:1234",
"http://localhost:5173",
"http://125.250.17.196:1234"
).toArray(String[]::new);
}
}

134 changes: 66 additions & 68 deletions src/main/java/com/khu/gitbox/auth/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.khu.gitbox.auth.config;

import com.khu.gitbox.auth.filter.JwtAuthenticationFilter;
import com.khu.gitbox.auth.handler.JwtAccessDeniedHandler;
import com.khu.gitbox.auth.handler.JwtAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -15,83 +19,77 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;

import com.khu.gitbox.auth.filter.JwtAuthenticationFilter;
import com.khu.gitbox.auth.handler.JwtAccessDeniedHandler;
import com.khu.gitbox.auth.handler.JwtAuthenticationEntryPoint;

import lombok.RequiredArgsConstructor;

@Configuration
@EnableMethodSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {
private static final String[] PUBLIC_URLS = {
"/api/register", "/api/login",
"/swagger-ui/**",
"/swagger-ui",
"/swagger-ui.html",
"/swagger/**",
"/swagger-resources/**",
"/v3/api-docs/**"
};
private static final String[] PUBLIC_URLS = {
"/api/register", "/api/login",
"/swagger-ui/**",
"/swagger-ui",
"/swagger-ui.html",
"/swagger/**",
"/swagger-resources/**",
"/v3/api-docs/**"
};

private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}

/**
* permitAll 권한을 가진 엔드포인트에 적용되는 SecurityFilterChain
*/
@Bean
public SecurityFilterChain securityFilterChainPermitAll(HttpSecurity http) throws Exception {
configureSecurityDefaults(http);
http.securityMatchers(matchers -> matchers.requestMatchers(PUBLIC_URLS))
.authorizeHttpRequests(authorize -> authorize.requestMatchers(PUBLIC_URLS).permitAll());
return http.build();
}
/**
* permitAll 권한을 가진 엔드포인트에 적용되는 SecurityFilterChain
*/
@Bean
public SecurityFilterChain securityFilterChainPermitAll(HttpSecurity http) throws Exception {
configureSecurityDefaults(http);
http.securityMatchers(matchers -> matchers.requestMatchers(PUBLIC_URLS))
.authorizeHttpRequests(authorize -> authorize.requestMatchers(PUBLIC_URLS).permitAll());
return http.build();
}

/**
* 인증 및 인가가 필요한 엔드포인트에 적용되는 SecurityFilterChain
*/
@Bean
public SecurityFilterChain securityFilterChainAuthorized(HttpSecurity http) throws Exception {
configureSecurityDefaults(http);
http
.addFilterBefore(jwtAuthenticationFilter, ExceptionTranslationFilter.class)
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler))
.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated());
return http.build();
}
/**
* 인증 및 인가가 필요한 엔드포인트에 적용되는 SecurityFilterChain
*/
@Bean
public SecurityFilterChain securityFilterChainAuthorized(HttpSecurity http) throws Exception {
configureSecurityDefaults(http);
http
.addFilterBefore(jwtAuthenticationFilter, ExceptionTranslationFilter.class)
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler))
.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated());
return http.build();
}

@Bean
public FilterRegistrationBean<JwtAuthenticationFilter> filterRegistration(JwtAuthenticationFilter filter) {
FilterRegistrationBean<JwtAuthenticationFilter> registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
public FilterRegistrationBean<JwtAuthenticationFilter> filterRegistration(JwtAuthenticationFilter filter) {
FilterRegistrationBean<JwtAuthenticationFilter> registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}

private void configureSecurityDefaults(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
}
private void configureSecurityDefaults(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.khu.gitbox.auth.filter;

import static org.springframework.util.StringUtils.*;

import java.io.IOException;

import com.khu.gitbox.auth.provider.JwtTokenProvider;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
Expand All @@ -12,48 +16,42 @@
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.khu.gitbox.auth.provider.JwtTokenProvider;
import java.io.IOException;

import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import static org.springframework.util.StringUtils.hasText;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final String AUTHENTICATION_SCHEME = "Bearer ";
private final JwtTokenProvider jwtTokenProvider;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String accessToken = parseJwt(request);
jwtTokenProvider.validateAccessToken(accessToken);
Authentication authentication = jwtTokenProvider.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (ExpiredJwtException ex) {
logger.warn("ExpiredJwtException Occurred : ", ex);
throw new CredentialsExpiredException("토큰의 유효기간이 만료되었습니다.", ex);
} catch (Exception ex) {
logger.warn("JwtAuthentication Failed. : ", ex);
throw new BadCredentialsException("토큰 인증에 실패하였습니다.");
}

filterChain.doFilter(request, response);
}

private String parseJwt(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
log.info(">>>>>> AccessToken : {}", bearerToken);
if (hasText(bearerToken) && bearerToken.startsWith(AUTHENTICATION_SCHEME)) {
return bearerToken.substring(AUTHENTICATION_SCHEME.length());
}
throw new AuthenticationCredentialsNotFoundException("토큰이 존재하지 않습니다.");
}
private static final String AUTHENTICATION_SCHEME = "Bearer ";
private final JwtTokenProvider jwtTokenProvider;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String accessToken = parseJwt(request);
jwtTokenProvider.validateAccessToken(accessToken);
Authentication authentication = jwtTokenProvider.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (ExpiredJwtException ex) {
logger.warn("ExpiredJwtException Occurred : ", ex);
throw new CredentialsExpiredException("토큰의 유효기간이 만료되었습니다.", ex);
} catch (Exception ex) {
logger.warn("JwtAuthentication Failed. : ", ex);
throw new BadCredentialsException("토큰 인증에 실패하였습니다.");
}

filterChain.doFilter(request, response);
}

private String parseJwt(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
log.info(">>>>>> AccessToken : {}", bearerToken);
if (hasText(bearerToken) && bearerToken.startsWith(AUTHENTICATION_SCHEME)) {
return bearerToken.substring(AUTHENTICATION_SCHEME.length());
}
throw new AuthenticationCredentialsNotFoundException("토큰이 존재하지 않습니다.");
}
}
36 changes: 17 additions & 19 deletions src/main/java/com/khu/gitbox/auth/presentation/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
package com.khu.gitbox.auth.presentation;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.khu.gitbox.auth.application.AuthService;
import com.khu.gitbox.auth.presentation.dto.AuthResponse;
import com.khu.gitbox.auth.presentation.dto.LoginRequest;
import com.khu.gitbox.common.response.ApiResponse;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class AuthController {

private final AuthService authService;
private final AuthService authService;

@PostMapping("/login")
public ResponseEntity<ApiResponse<AuthResponse>> login(@Valid @RequestBody LoginRequest request) {
AuthResponse authResponse = authService.login(request);
@PostMapping("/login")
public ResponseEntity<ApiResponse<AuthResponse>> login(@Valid @RequestBody LoginRequest request) {
AuthResponse authResponse = authService.login(request);

// 쿠키 생성
return ResponseEntity.ok()
.header("Set-Cookie", getAccessTokenHeader(authResponse.accessToken()))
.body(ApiResponse.ok(authResponse));
}
// 쿠키 생성
return ResponseEntity.ok()
.header("Set-Cookie", getAccessTokenHeader(authResponse.accessToken()))
.body(ApiResponse.ok(authResponse));
}

private String getAccessTokenHeader(String accessToken) {
return "accessToken=" + accessToken + "; Path=/; HttpOnly; SameSite=None; Secure";
}
private String getAccessTokenHeader(String accessToken) {
return "accessToken=" + accessToken + "; Path=/; HttpOnly; SameSite=None; Secure";
}
}
Loading

0 comments on commit c674437

Please sign in to comment.