Spring Boot
[OAuth] OAuth2 ์ค์ ํ์ผ ์์ฑ
์ฐ์ฃผ๋ฌผ๊ณ ๊ธฐ
2025. 5. 11. 23:43
๋ฐ์ํ
OAuth2๋ฅผ ๊ธฐ์กด JWT์ ํจ๊ป ์ฐ๋ ค๋ฉด
๊ธฐ์กด์ ์์ฑํด๋ ์ค์ ์ด ์๋๋ผ ๋ค๋ฅธ ์ค์ ์ ์จ์ผํจ.
1. ๊ธฐ์กด ํผ ๋ก๊ทธ์ธ ๋ฐฉ์์ ์ป๋ WebSecurityConfig.java ํ์ผ ์ ๋ถ ์ฃผ์์ฒ๋ฆฌ~~~~~
2 . config ํจํค์ง์ WebOauthSecurityConfig.java ์์ฑ
@RequiredArgsConstructor
@Configuration
public class WebOAuthSecurityConfig {
private final OAuth2UserCustomService oAuth2UserCustomService;
private final TokenProvider tokenProvider;
private final RefreshTokenService refreshTokenService;
private final UserService userService;
@Bean
public WebSecurityCustomizer configure() { // ์คํ๋ง ์ํ๋ฆฌํฐ ๊ธฐ๋ฅ ๋นํ์ฑํ
return (web) -> web.ignoring()
.requestMatchers(
new AntPathRequestMatcher("/img/**"),
new AntPathRequestMatcher("/css/**"),
new AntPathRequestMatcher("/jss/**")
);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// ํ ํฐ ๋ฐฉ์์ผ๋ก ์ธ์ฆ์ ํ๊ธฐ ๋๋ฌธ์, ๊ธฐ์กด์ ์ฌ์ฉํ๋ ํผ ๋ก๊ทธ์ธ, ์ธ์
๋นํ์ฑํ
return http
.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)
.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/api/token")).permitAll()
.requestMatchers(new AntPathRequestMatcher("/api/**")).authenticated().anyRequest().permitAll())
.oauth2Login(oauth2 -> oauth2.loginPage("/login")
.authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint.authorizationRequestRepository(oAuth2AuthorizationRequestBasedOnCookieRepository()))
.userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint.userService(oAuth2UserCustomService))
.successHandler(oAuth2SuccessHandler())
)
.exceptionHandling(exceptionHandling -> exceptionHandling
.defaultAuthenticationEntryPointFor(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AntPathRequestMatcher("/api/**")
))
.build();
}
@Bean
public OAuth2SuccessHandler oAuth2SuccessHandler() {
return new Oauth2SuccessHandler(
tokenProvider,
refreshTokenRepository,
oAuth2AuthorizationRequestBasedOnCookieRepository(),
userService
);
}
@Bean
public TokenAuthenticationFilter tokenAuthenticationFilter() {
return new TokenAuthenticationFilter(tokenProvider);
}
@Bean
public OAuth2AuthorizationRequestBasedOnCookieRepository oAuth2AuthorizationRequestBasedOnCookieRepository() {
return new OAuth2AuthorizationRequestBasedOnCookieRepository();
}
@Bean
public BCryptPasswordEncoder bCryptpasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
๊ฐ์๊ธฐ ๋ฐฉ๋ํด์ง ์์ ๋ํต์ด ์ค๋ ์ค
ํ๋ฃจ ๋ ์ก๊ณ ์ด๋ถ๋ถ ๋ค ๊ณต๋ถํด์ผํ ๋ฏ

๋ฐ์ํ