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
'짧은 프로젝트' 카테고리의 다른 글
Springboot jwt 로그인3(redis 리프레시토큰) (0) | 2024.01.12 |
---|---|
Springboot Jwt 로그인2(로그인 처리 후 쿠키 발급) (0) | 2024.01.12 |
Springboot 배달 시스템 만들기 3(위치정보 전송 및 표시하기 카카오지도) (0) | 2024.01.10 |
Springboot 배달 시스템 만들기 2(배달방 생성,삭제,메세지전송) (0) | 2024.01.10 |
Springboot 배달 시스템 만들기 1(웹소켓 기본세팅) (0) | 2024.01.09 |