개인 자료 정리 홈페이지 입니다.

Note > 스프링시큐리티 jwt 적용하기로그인 페이지 설정과 로그인 처리부분

By a3040, Published on Invalid Date


  1. 로그인 페이지 설정
  2. 로그인 처리후 토큰 발급 : 간단히 정의한 provider[ db에서 id를 기준으로 찾아온] id, pwd와 로그인 폼에서 받은 id, pwd를 비교합니다.


로그인 페이지 설정

@Configuration
public class SecurityConfig {
...

    @Bean
    public SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) throws Exception {
...

        http.authorizeHttpRequests((requests) -> requests
...
                .requestMatchers("/css/**", "/js/**", "/error").permitAll() // 정적자원 허용
                .requestMatchers("/member/loginProc").permitAll() // html막테스트
                .formLogin((form) -> form
                        .loginPage("/member/login").permitAll()
...
                )
                .logout((logout) -> logout.permitAll()
                        .deleteCookies("jwt")
                        .invalidateHttpSession(false)
                        .logoutSuccessUrl("/member/login"));


        return http.build();
    }


로그인 처리 및 토큰 발급


@RestController
public class AuthenticationController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/member/loginProc")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) throws Exception {
        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        } catch (BadCredentialsException e) {
            throw new Exception("Incorrect username or password", e);
        }
        final User user = userRepository.findByUsername(loginRequest.getUsername());
        final UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(user.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new LoginResponse(token));
    }

    // ...
}




            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));


이 과정에서 일어나는 일


  1. UsernamePasswordAuthenticationToken 객체를 생성합니다. 이 객체에는 사용자가 입력한 로그인 폼 정보가 포함됩니다.
  2. AuthenticationManager 구현체 중 하나인 ProviderManager 객체를 생성합니다. 이 객체는 여러 개의 AuthenticationProvider를 가질 수 있습니다.
  3. ProviderManagerauthenticate() 메서드를 호출합니다. 이 메서드는 등록된 AuthenticationProvider에서 인증을 처리합니다.
  4. DaoAuthenticationProvider 객체를 생성하여 ProviderManager에 추가합니다. 이 객체는 DB에서 사용자 정보를 가져와 인증을 처리합니다.
  5. DaoAuthenticationProvideradditionalAuthenticationChecks() 메서드를 호출하여 사용자 정보를 인증합니다. 이 메서드에서는 DB에서 가져온 사용자 정보와 로그인 폼 정보를 비교합니다.



Note > 스프링시큐리티 jwt 적용하기jwt토큰을 이용한 권한 확인 필터

By a3040, Published on Invalid Date

SecurityFilterChain에 jwt토큰 관련 설정을 추가해서 권한에 따라 접근을 허가합니다.


@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String authToken = extractAuthTokenFromRequest(request);
        if (authToken != null) {
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = jwtUserDetailsService.loadUserByJwtToken(authToken);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }


    private String extractAuthTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }
        return null;
    }
}
Note > vscode에서 react debugger 설정설정하기

By a3040, Published on Invalid Date

프로젝트 폴더/.vscode/launch.json 에

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "msedge",
      "request": "launch",
      "name": "Launch Edge against localhost",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}"
    }
  ]
}


내용을 추가 하거나 launch.json파일을 visual studio code에서 열면있는 "add configureation" 버튼를 눌러서 생성합니다.

저 참조위치가면 영상이 있습니다.


이후 프로젝트에서 react를 실행 합니다.

npm start

그리고 나서 vscode에서 방금 설정한 "Launch Edge against localhost"를 실행합니다.


새창이 띄면서 react가 실행된 창이 보입니다.


"url": "http://localhost:3000",  이부분의 포트나 위치는 npm start 에서설정한 포트나 내가 보고 싶은 페이지 주소입니다.
"url": "http://localhost:8080/Memo",