inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

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

BCryptPasswordEncoder 관련 Error

3058

작성자 없음

작성한 질문수 0

0

package com.junyharang.jwtstudy.config.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.junyharang.jwtstudy.auth.PrincipalDetails;
import com.junyharang.jwtstudy.model.Member;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 스프링 시큐리티에 UsernamePasswordAuthenticationFilter가 있다.
// /login이 요청 오면 username, password를 전송하면 (Post)
// UsernamePasswordAuthenticationFilter가 동작한다.
// 현재는 SecurityConfig에서 FormLogin disable을 시켜서 동작하지 않는다.
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;

@Override // /login 요청이 들어오면 로그인 시도를 위해 실행되는 Method
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

System.out.println("JwtAuthenticationFilter : 로그인 시도 중 입니다!");

// 1. username, password를 받는다.
try {
// BufferedReader reader = request.getReader();
//
// String input = null;
//
// while ((input = reader.readLine()) != null) {
// System.out.println(input);
// } // while 문 끝

// JSON으로 전달된 값을 Parsing 할수 있게 해주는 객체 생성
ObjectMapper om = new ObjectMapper();
Member member = om.readValue(request.getInputStream(), Member.class);
System.out.println(member);

// Token 생성(회원의 이름과 Password를 통해)
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(member.getUsername(), member.getPassword());

// PrincipalDetailsService loadUserByUsername()이 실행 된다.
// authenticationManager Token을 넣어 호출한다.
// authentication 변수에는 Login 정보가 담긴다.
Authentication authentication = authenticationManager.authenticate(authenticationToken);

// authentication 객체가 Session 영역에 저장된다.
PrincipalDetails principal = (PrincipalDetails) authentication.getPrincipal();

// 출력이 된다면 Login이 되었다는 의미
System.out.println(principal.getMember().getUsername());

return authentication;
} catch (IOException e) {
e.printStackTrace();
} // try-cache 문 끝

System.out.println("===========================================");
// 2. authenticationManager로 정상 인지 로그인 시도하면 PrincipalDetailsService가 호출된다.
// 해당 Class안에 loadUserByUsername()가 자동 호출

// 3. PrincipalDetails Session에 담는다.
// Session에 해당 내용을 담는 이유는 담지 않으면 권한에 대한 처리를 할 수 없기 때문이다.

// 4. JWT를 만들어서 응답해 준다.

return null;
} // attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
} // class
 
안녕하세요? 25강에 해당 부분을 하다가 DB에 회원값이 들어가 있는 걸 보고, 회원가입 로직이 누락 되었다는 부분을 찾기 위해 Controller를 보고 아래 내용을 추가 하였습니다.
 
@PostMapping("join") public String join(@RequestBody Member member) {
member.setPassword(bCryptPasswordEncoder.encode(member.getPassword()));
member.setRolse("ROLE_USER");
memberRepository.save(member);
return "회원가입완료";
}

 

그리고 나서 SecurityConfig에 아래 내용을 추가 하였구요.

@Autowired private MemberRepository memberRepository;

@Autowired private CorsConfig corsConfig;

@Bean public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
} // passwordEncoder()

private final CorsFilter corsFilter;

 

근데 아래와 같은 Error가 발생 합니다.

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-01-19 00:25:02.184 ERROR 17752 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 1 of constructor in com.junyharang.jwtstudy.controller.RestAPIController required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found. Action: Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.

jwt Spring Security spring

답변 1

0

최주호

해당 코드를 main() 이 있는 자바 파일에 옮겨보세요.

 

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

0

104

1

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

0

405

1

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

0

133

1

수료증 문의

0

234

2

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

0

123

1

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

0

323

1

이전 강의 참고하라는 말씀

0

254

1

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

2

1124

2

구글 소셜 로그인 302

0

204

1

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

1

588

1

[자바] 시큐리티 Config 참고

13

956

1

이론강의

0

283

1

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

0

495

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

930

3

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

0

685

2

특정 url필터 거는 방법 이슈

0

426

1

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

0

280

1

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

1

1049

2

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

0

302

1

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

0

703

1

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

0

344

1

jwt와 실제데이터의 관계

1

249

1

jwt 와 세션ID의 관계

1

317

1

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

0

425

1