짧은 프로젝트

Spring boot jwt 로그인 하기1 (기본세팅)

디비드킴 2024. 1. 11. 13:09

1.필요 필터 작성

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsfilter() {
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration=new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOriginPattern("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(source);
    }
}
@Slf4j
public class LoginFilter  extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    public LoginFilter(AuthenticationManager authenticationManager){
        this.authenticationManager=authenticationManager;
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)throws AuthenticationException {
        log.info("로그인 필터 입장");
        ObjectMapper objectMapper=new ObjectMapper();
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject = objectMapper.readValue(request.getInputStream(), JSONObject.class);
            log.info("로그인시도 정보:{}",jsonObject);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(jsonObject.get("id"),jsonObject.get("pwd")));
        } catch (IOException e) {
            log.error("요청에서 JSON 데이터를 읽는 중 오류 발생", e);
            throw new AuthenticationServiceException("요청에서 JSON 데이터를 읽는 중 오류 발생", e);
        }

    }
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        log.info("로그인 성공");
    }
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        log.info("로그인실패:{}",failed.getMessage());

    }

}
@Slf4j
public class AuthorizationFilter extends BasicAuthenticationFilter {

    public AuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("인증필터 입장");
        chain.doFilter(request, response);
    }

}

 

2.시큐리티설정

@Configuration//빈등록: 스프링 컨테이너에서 객체에서 관리
@EnableWebSecurity/////필터를 추가해준다
@RequiredArgsConstructor
public class SecurityConfig {

    private final CorsConfig corsConfig;
    private final AuthenticationConfiguration authenticationConfiguration;

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

    @Bean
    public BCryptPasswordEncoder pwdEncoder() {
        return  new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                //.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                //.and()
                .addFilter(corsConfig.corsfilter())
                .formLogin().disable().httpBasic().disable()
                .authorizeRequests()
                .antMatchers("/pass/**","/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new LoginFilter(authenticationManager(authenticationConfiguration)))
                .addFilter(new AuthorizationFilter(authenticationManager(authenticationConfiguration)))
        ;

        return http.build();

    }
}

 

 

3.그외 로그인 정보 로직 추가

@Data
@Slf4j
public class PrincipalDetails implements UserDetails {

    private String email;
    private String pwd;

    public PrincipalDetails(String email,String pwd){
        this.email=email;
        this.pwd=pwd;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String role = "ROLE_USER";
        Collection<GrantedAuthority> roles = new ArrayList<>();
        roles.add(new SimpleGrantedAuthority(role));
        return roles;
    }

    @Override
    public String getPassword() {
        return pwd;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<String> tempInfo = tempInfo(username);
        return new PrincipalDetails(username, tempInfo.get(1));
    }
    private List<String>tempInfo(String username){
        List<String> tempInfo = new ArrayList<>();
        if(username.equals("kim")){
            tempInfo.add("kim");
            tempInfo.add("$2a$12$qMfj1gc1MQnJReMJwq1zH.u85uqp/0V3Ij/LqBdeITiJmNcwyjwfS");
        }else{
            tempInfo.add("kim2");
            tempInfo.add("$2a$12$KxYh2x/YI4TY5qYuwicYKe4Kr7fPlA7aLqvmE18bJaJ/2fRIPa95.");
        }
        return tempInfo;
    }
}

 

테스트

 

https://github.com/novb1492/login/tree/basic-setting

 

GitHub - novb1492/login

Contribute to novb1492/login development by creating an account on GitHub.

github.com