Step-by-Step
[Spring] 12. 스프링 시큐리티 본문
프로젝트 끝나고 작성하는 글
Spring Security를 추가했다.
https://github.com/gmlwn7245/SpringSecurity_Study
별도의 프로젝트를 생성해서 연습한 후에 적용하였다.
일단 비회원일때 보낼 수 있는 요청은 1. 회원가입 2. 로그인 이고,
http.authorizeHttpRequests().antMatchers("/","/auth/**").permitAll()
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated(); // 그 외 모든 요청은 인증 필요
이런식으로 컨트롤러중에 루트 '/'와 '/auth/**' 형식의 주소는 허락하였다.
ROLE은 USER와 ADMIN으로 나누었는데, '/admin'은 역할이 ADMIN인 사람만 접근 가능하며,
나머지는 모두 인증과정을 거쳐야 한다.
package com.security.model;
public enum UserRole {
USER,
ADMIN;
public String getRoleType() {
return "ROLE_" + this.name();
}
}
역할들을 저장하고 출력하는 enum 을 작성하였다
사용자 정보를 담는 인터페이스인 UserDetails 와
사용자 정보를 가져오는 인터페이스 UserDetailsService를 상속받아 구현하는 클래스를 작성했다.
잘 구현하다가 Configuration 작성할 때, WebSecurityConfigurerAdapter를 확장하여 이용하였는데
갑자기 줄이 쳐지더니 사용할 수 없다고 뜨는 것이었다...
Spring Security 관련 공식 문서를 찾아보니까 Spring 5.7부터 사용하지 않는다고 한다.
바뀐지 얼마 되지 않아서 인터넷이랑 깃허브 다 찾아봐도 안나오길래 그냥 하나하나 코드 따라가면서 구현하였다.
@Configuration
@Configuration
public class SecurityConfig {
// Spring 5.7 부터 WebSecurityConfigurerAdapter 사용 X..
// 회원가입시 비밀번호 암호화에 사용할 Encoder 빈 등록
@Bean
public BCryptPasswordEncoder encodePassword() {
return new BCryptPasswordEncoder();
}
// configure 부분
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeHttpRequests();
http.authorizeHttpRequests().antMatchers("/","/auth/**").permitAll()
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated(); // 그 외 모든 요청은 인증 필요
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
이렇게 하고 POSTMAN이용해서 테스트해보았는데
로그인하지 않고 인증 과정을 거쳐야하는 요청이 들어오면, 403 Forbidden이 나왔다.
로그인을 하면 JSESSIONID가 발급되었고, 다른 요청도 가능하게 된다
이후 안드로이드 스튜디오에서 쿠키를 받아서 등록하는데
https://easy-coding.tistory.com/54
이 블로그를 많이 참조하였고
CookieJar이랑 CookieManager를 이용하여 작성하였다.
'프로젝트 > Eggo (Mobile App)' 카테고리의 다른 글
[Spring] 13. 프로젝트 구조 변경 (feat. Flask) (0) | 2022.06.21 |
---|---|
[Spring] 11. Android - Spring - DB - Python 데이터 주고받기 (0) | 2022.05.21 |
[Spring] 10. DB에 이미지 저장 - BLOB (+ Python에서 열기) (0) | 2022.05.21 |
[Spring] 9. 안드로이드 통신 - HttpUrlConnection (0) | 2022.05.21 |
[Spring] 8. 날씨 API 받아오기 (0) | 2022.05.19 |