inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링부트 시큐리티 & JWT 강의

스프링부트 시큐리티 25강 - jwt를 위한 강제 로그인 진행

25강 마지막 테스트에서 오류

1044

작성자 없음

작성한 질문수 0

1

-25강 마지막 테스트 부분에서 실행 오류가 발생합니다.

PrincipalDetailsService's loadUserByUsername()도 실행이 확인이 안됩니다.

 

java.lang.NullPointerException: Cannot invoke "org.springframework.security.authentication.AuthenticationManager.authenticate(org.springframework.security.core.Authentication)" because "this.authenticationManager" is null
	at com.oopsw.myboot.config.jwt.JwtAuthenticationFilter.attemptAuthentication(JwtAuthenticationFilter.java:63) ~[classes/:na]

전체 코드는 다음과 같습니다.

@RequiredArgsConstructor //4.1
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter{

	private final AuthenticationManager authenticationManager; //4.1
	
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {	
		
		try {
			
			ObjectMapper om=new ObjectMapper();
			Users user=om.readValue(request.getInputStream(), Users.class);
			System.out.println(user);
			
			UsernamePasswordAuthenticationToken authenticationToken
			=new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
			
			
			Authentication authentication
			=authenticationManager.authenticate(authenticationToken); 
			
			PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal();
			System.out.println(principalDetails.getUser().getUsername()); 
			return authentication;
		} catch (IOException e) {			
			e.printStackTrace();
		}			
		return null;
	}

	
}

 

spring spring-security jwt

답변 2

0

루키000

SecurityConfig.java 다음과 같이 변경해보세요.

시큐리티 버전이 업그레이드 되면서 AuthenticationManager 를 따로 빼서 @Bean 을 만들어야 null 오류가 없어지네요.


@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록
public class SecurityConfig {

    @Autowired
    private CorsConfig corsConfig;

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
        //AuthenticationManager authenticationManager =  http.getSharedObject(AuthenticationManager.class);

        http.csrf(AbstractHttpConfigurer::disable);
        http
                .sessionManagement(sc -> sc.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 세션을 사용하지 않음.
                .addFilter(corsConfig.corsFilter()) // @CrossOrigin(인증X), 시큐리티 필터에 등록 인증(O) --> 모든 요청 허용.
                //.addFilterBefore(new MyFilter3(), SecurityContextPersistenceFilter.class) // ---> 22, 23강 테스트용.
                .addFilter(new JwtAuthenticationFilter(authenticationManager)) // AuthenticationManager ---> 24강 테스트
                .formLogin((form)-> form.disable())
                .httpBasic((basic)-> basic.disable())
                /* --------- security 최신 버전에서는 권한 적용시 ROLE_ 쓰지 않음. 즉, USER, ADMIN, MANAGER로 써야함 ---------- */
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/static**", "/logout/**", "/login/**").permitAll()
                        .requestMatchers("/api/v1/user/**").authenticated() // /user라는 url로 들어오면 인증이 필요하다.
                        .requestMatchers("/api/v1/manager/**").hasAnyRole("MANAGER", "ADMIN") // manager으로 들어오는 MANAGER 인증 또는 ADMIN인증이 필요하다는 뜻이다.
                        .requestMatchers("/api/v1/admin/**").hasRole("ADMIN") // //admin으로 들어오면 ADMIN권한이 있는 사람만 들어올 수 있음
                        .anyRequest().permitAll() // 그리고 나머지 url은 전부 권한을 허용해준다.
                );
        return http.build();
    }
}

 

 

0

인프런 AI 인턴

안녕하세요, 인프런 AI 인턴입니다.

hyeyoung jeon님의 문제는 JwtAuthenticationFilter에서 authenticationManagernull이라는 것이 원인으로 보입니다. authenticationManager가 제대로 주입되지 않았거나 설정되지 않았을 가능성이 있습니다. 스프링 시큐리티에서 AuthenticationManager를 사용하기 위해서는 해당 빈을 명시적으로 설정해줄 필요가 있습니다.

다음은 AuthenticationManagerJwtAuthenticationFilter에 주입하는 방법에 대해 설명합니다.

  1. WebSecurityConfigurerAdapter를 확장하는 설정 클래스에서 AuthenticationManager를 노출하는 메서드를 오버라이드합니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
  1. JwtAuthenticationFilterAuthenticationManager에 접근할 수 있도록, 위에서 노출한 AuthenticationManager 빈을 JwtAuthenticationFilter에 주입합니다.

현재 JwtAuthenticationFilter 클래스는 @RequiredArgsConstructor 어노테이션을 사용하여 final 필드에 대한 생성자를 자동으로 생성하고 있는데, 이는 롬복(Lombok) 라이브러리의 기능입니다. AuthenticationManager가 제대로 주입되지 않았다면, 스프링 시큐리티 설정 클래스에서 AuthenticationManager 빈을 명시적으로 정의하고 주입하는 과정을 확인해보세요.

스프링 시큐리티 설정이 올바르게 되어 있음에도 authenticationManagernull로 나타나는 경우, JwtAuthenticationFilter의 초기화 과정과 authenticationManager 주입 과정을 다시 점검해보시기 바랍니다.

JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?

0

94

1

Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?

0

401

1

13:23 system.out 출력문이 다르게 나옵니다.

0

130

1

수료증 문의

0

226

2

9분대에 질문이 있습니다 !

0

114

1

password 비교를 하지 않았는데 어떻게 인증이 통과된 건가요?

0

320

1

이전 강의 참고하라는 말씀

0

253

1

강의 실습하다가 막히는 분들 참고(2024년8월 기준)

2

1116

2

구글 소셜 로그인 302

0

200

1

오류 문의 _ org.springframework.orm.jpa.JpaSystemException: could not deserialize

1

584

1

[자바] 시큐리티 Config 참고

13

953

1

이론강의

0

280

1

SpringSecurity JWT 로그인 URL 2개 설정하는 방법

0

487

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

921

3

구글 로그인시 authentication이 null 값이라고 에러가 발생합니다.

0

677

2

특정 url필터 거는 방법 이슈

0

422

1

강사님께서 말씀하시는 시큐리티세션이 SecurityContext인가요?

0

277

1

jwt를 저장하는 위치에 궁금한 점이 있습니다.

0

298

1

mustache를 사용하지 않고 thymeleaf를 사용하려고 하는데

0

696

1

세션 인증방식이 REST 원칙에 위배되는 건가요?

0

338

1

jwt와 실제데이터의 관계

1

242

1

jwt 와 세션ID의 관계

1

312

1

SecurityConfig에서 세션 설정, 인가 설정

0

417

1

섹션2 9강까지 듣고 질문이 있습니다. 스프링부트 버전을 다운그레이드해도 될까요?

0

394

1