• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

AbstractAuthenticationProcessingFilter내에서 HttpServletResponse값이 안들어갑니다

23.06.29 16:20 작성 23.06.29 16:22 수정 조회수 438

1

	@Bean
	public SecurityFilterChain httpSecurity(HttpSecurity http) throws Exception {
		return http.cors().disable()
			.csrf().disable()
			.httpBasic().disable()
			.formLogin().disable()
			.authorizeRequests().anyRequest().authenticated()
			.and()
			.addFilterAt(authFilter(), UsernamePasswordAuthenticationFilter.class)
			.addFilterAt(jwtFilter(), UsernamePasswordAuthenticationFilter.class)
			.build();
	}

	@Bean
	public WebSecurityCustomizer webSecurityCustomizer() {
		return web -> {
			web.ignoring().requestMatchers().antMatchers("/h2/**");
		};
	}


	@Bean
	public AuthFilter authFilter() throws Exception {
		var authFilter = new AuthFilter();
		authFilter.setAuthenticationManager(authenticationConfiguration.getAuthenticationManager());
		authFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/"));
		authFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/error"));

		return authFilter;
	}

설정은 위와 같이 했습니다.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
   Authentication authResult) throws IOException, ServletException {
   super.successfulAuthentication(request, response, chain, authResult);
   String SECRET = "secrsdkfjhjh4243j234jh2SDdsfjhgsdfhjgjFQQQQdasd1et";
   Claims claims = Jwts.claims();
   claims.put("username", SecurityContextHolder.getContext().getAuthentication().getName());
   String compact = Jwts.builder()
      .setClaims(claims)
      .setIssuedAt(new Date(System.currentTimeMillis()))
      .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 1시간
      .signWith(SignatureAlgorithm.HS256, SECRET)
      .compact();

   response.addHeader("Authorization", compact);
   response.addCookie(new Cookie("token", compact));
}

위와 같이 설정을 했는데 http 요청 테스트를 해보면 설정한 값이 하나도 들어가 있지않습니다.

컨트롤러나 OncePerRequestFilter에서 값을 넣어보면 잘 적용됩니다..

답변 2

·

답변을 작성해보세요.

0

godrn1993님의 프로필

godrn1993

질문자

2023.06.30

https://github.com/devhanliam/securiy-debug/tree/main/src/main

답변 감사합니다.

이해하신대로 successfulAuthentication attemptAuthentication에서도 response에 헤더에 값을 넣어도 AbstractAuthenticationProcessingFilter를 상속한 필터에서만 그런 현상이 발견됩니다. 조회되지 않습니다.

안녕하세요. 호돌맨입니다.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
   Authentication authResult) throws IOException, ServletException {

   super.successfulAuthentication(request, response, chain, authResult); // <-- 이 부분
   String SECRET = "secrsdkfjhjh4243j234jh2SDdsfjhgsdfhjgjFQQQQdasd1et";
   Claims claims = Jwts.claims();
   // ... 생략
}

위 코드에서 super.successfulAuthentication(request, response, chain, authResult); 라인을 삭제하시기 바랍니다.

위 코드를 추적해보면 내부적으로 인증관련 세션 생성 후 redirect를 먼저 하기 때문에 이후에 godrn1993님이 설정하신 header 설정이 무의미 한 걸 알수 있습니다.

Intellij 디버그 모드 사용 방법을 익히시는 걸 추천드립니다.

감사합니다.

godrn1993님의 프로필

godrn1993

질문자

2023.07.13

정말 감사합니다.

그 부분은 아예 신경 안쓰고 다른 부분만 포인트 찍으면 왜 안될까만 생각했네요.

창피하네요,,ㅜㅜ 감사합니다

0

안녕하세요. 호돌맨입니다.
질문을 남겨주셔서 감사합니다.

설정한 값이 하나도 들어가 있지않습니다. 라고 말씀하신 거는 응답 헤더에 값이 포함되지 않는다는 말씀이실까용?

코드가 전체적으로 공개되어 있지 않아 최대한 비슷하게 작성 해봤는데 저는 successfulAuthentication 메서드까지 잘 호출이 됩니다.

breakpoint 를 설정하시고 디버그모드로 해당 메서드까지 호출되는지 확인 해보시면 좋을것 같습니다.

코드를 github에 올려주시면 받아서 확인 해보도록 하겠습니다.

감사합니다.