JWT 적용하기 (3)

jb kim·2022년 3월 12일
0

REST API 블로그 앱

목록 보기
55/65

시큐리티 설정에 적용

7. SecurityConfig

베이직 인증을 제거하고 JwtAuthenticationEntryPoint 주입

public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private JwtAuthenticationEntryPoint authenticationEntryPoint;
	
	@Bean
	public JwtAuthenticationFilter jwtAuthenticationFilter() {
		return new JwtAuthenticationFilter();
	}

	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
		
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http
			.csrf().disable()
			.exceptionHandling()
			.authenticationEntryPoint(authenticationEntryPoint)
			.and()
			.sessionManagement()
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
			.and()
			.authorizeRequests()
			.antMatchers(HttpMethod.GET, "/api/**").permitAll()
			.antMatchers("/api/auth/**").permitAll()
			.anyRequest()
			.authenticated();

		http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
	}

8. AuthController signin

TokenProvider 를 필드주입하고 로그인시 토큰 생성

	@Autowired
	private JwtTokenProvider tokenProvider;
	
	@PostMapping("/signin")
	public ResponseEntity<JWTAuthResponse> authenticateUser(@RequestBody LoginDto loginDto){
		Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
				loginDto.getUsernameOrEmail(), loginDto.getPassword()));
		
		SecurityContextHolder.getContext().setAuthentication(authentication);
		//jwtTokenProvider 으로 인증정보로 토큰 생성하기
		String token = tokenProvider.generateToken(authentication);
		
		return new ResponseEntity<>(new JWTAuthResponse(token), HttpStatus.OK);		
	}

일반 유저로 로그인해서 토큰을 받으면?

profile
픽서

0개의 댓글