3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2024년 10월 19일 07:41 #131509
니리참가자@Configuration @EnableWebSecurity public class SecurityConfig {
@Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); }
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(AbstractHttpConfigurer::disable); http.addFilterBefore(new JwtFilter(), ExceptionTranslationFilter.class); http.sessionManagement((session)->session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.cors(cors->cors.configurationSource(corsConfigurationSource()));
http.formLogin(AbstractHttpConfigurer::disable); http.httpBasic(AbstractHttpConfigurer::disable); http.authorizeHttpRequests(auth->auth.requestMatchers("/**").permitAll() .anyRequest().authenticated());
return http.build(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // React 개발 서버 주소 configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.addAllowedOrigin("http://localhost:5173"); configuration.setAllowCredentials(true); // 자격 증명(쿠키 등) 허용
// 모든 경로에 대해 설정 적용 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
public class JwtFilter extends OncePerRequestFilter {
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Cookie[] cookies = request.getCookies();
if (cookies == null) { filterChain.doFilter(request, response); return; }
var jwtCookie = ""; for (Cookie cookie : cookies) { if (cookie.getName().equals("jwt")) { jwtCookie = cookie.getValue(); } } System.out.println("check token: "+jwtCookie);
Claims claim; try{ claim = JwtUtil.extractToken(jwtCookie); System.out.println("claim: "+claim); }catch (Exception e) { filterChain.doFilter(request, response); return; }
var arr = claim.get("authorities").toString().split(","); var authorities = Arrays.stream(arr).map(a->new SimpleGrantedAuthority(a)).toList();
var customUser = new CustomUser( claim.get("username").toString(), "none", authorities ); customUser.userIdx = claim.get("userIdx").toString(); customUser.userEmail = claim.get("userEmail").toString();
var authToken = new UsernamePasswordAuthenticationToken( customUser,"NONE_PROVIDED" ); System.out.println("authToken: "+authToken); authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); System.out.println("authToken details: "+authToken); SecurityContextHolder.getContext().setAuthentication(authToken);
filterChain.doFilter(request, response); } }
결과 token: eyJhbGciOiJIUzM4NCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJ1c2VyRW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwidXNlcklkeCI6IjEiLCJhdXRob3JpdGllcyI6IlVTRVIiLCJpYXQiOjE3MjkyOTA2NzksImV4cCI6MTcyOTI5MTI3OX0.koXxfmxpVFQqRjzrp_gorvOfPPyC0WZ-QcETUdrU0cR6P3ok3V9JaIIx3kI4LOoo check token: eyJhbGciOiJIUzM4NCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJ1c2VyRW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwidXNlcklkeCI6IjEiLCJhdXRob3JpdGllcyI6IlVTRVIiLCJpYXQiOjE3MjkyOTA2NzksImV4cCI6MTcyOTI5MTI3OX0.koXxfmxpVFQqRjzrp_gorvOfPPyC0WZ-QcETUdrU0cR6P3ok3V9JaIIx3kI4LOoo claim: {username=test, userEmail=test@test.com, userIdx=1, authorities=USER, iat=1729290679, exp=1729291279} authToken: UsernamePasswordAuthenticationToken [Principal=com.muneo.dealwith.Jwt.CustomUser [Username=test, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[USER]], Credentials=[PROTECTED], Authenticated=false, Details=null, Granted Authorities=[]] 토큰 유효기간 검사를 하려는데 프론트에서 토큰은 잘 넘어가는데 auth가 null인지 모르겠어요ㅠ
2024년 10월 19일 10:39 #131510
codingapple키 마스터서버로 요청할 때 SecurityContextHolder.getContext().setAuthentication(authToken); 이거도 잘 실행되나 주변에서 아무거나 출력해봅시다
2024년 10월 19일 19:38 #131518
니리참가자해결을 하긴했는데 authToken의 반환 값이 달라서 그렇다는데 사실 잘모르겠습니다
List<SimpleGrantedAuthority> authorities = Arrays.stream(claim.get("authorities").toString().split(",")) .map(SimpleGrantedAuthority::new) .toList();
var customUser = new CustomUser( claim.get("username").toString(), "none", authorities ); customUser.userEmail = claim.get("userEmail").toString(); customUser.nickName = claim.get("nickName").toString();
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( customUser,null,authorities ); System.out.println("authToken: "+authToken); authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
System.out.println("authToken details: "+authToken); SecurityContextHolder.getContext().setAuthentication(authToken);
filterChain.doFilter(request, response); 요렇게 하니까 잘 나옵니다
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.