-
[Spring] SpringBoot Security 회원가입 (react, nginx)기초/SPRING 2022. 3. 23. 21:54
*표시는 배경지식
*인프런 강좌
Dependency 등록
더보기implementation 'org.springframework.boot:spring-boot-starter-security:2.6.4'
Spring Security Filter 등록
더보기import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
//스프링 시큐리티 필터가 스프링 필터체인에 등록
public class SecurityConfig extends WebSecurityConfigurerAdapter{
}*WebSecurityConfigurerAdapter
더보기WebSecurityConfigurerAdapter (spring-security-docs 5.6.2 API)
Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods. Will automatically apply the result of looking up AbstractHttpConfigurer from SpringFactoriesLoader to allow deve
docs.spring.io
Deprecated.
The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2Oauth2를 권장하고 있음
*Spring Security는 기본적으로 제공되는 Filter Chain이 많다.
debug를 켜주면 등록된 체인을 확인할 수 있다.
더보기@EnableWebSecurity(debug=true)
configure Method Override
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("/user/**").authenticated() .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')") .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") .anyRequest().permitAll(). .and() .formLogin() .loginPage("/Login") .usernameParameter("userId") .loginProcessingUrl("/LoginProc") .defaultSuccessUrl("/"); }
.antMatchers("/path/**") : 경로지정
.authenticated() : 인가 ( ROLE 없음 )
.access("hasRole('ROLE_ADMIN')") : 인가 ( ROLE 지정 )
permitAll() : 인가없이 요청 허용
.and() : XML을 닫는 표현,
.formLogin() : 폼을 통한 로그인 활성화
.loginPage() : 로그인페이지 등록
.usernameParameter() : 로그인창에서 로그인 아이디로 사용되는 Form태그 하위의 Input태그 name속성 값
.loginProcessingUrl() : SpringSecurity 로그인 처리페이지 등록 ( 페이지를 안만들어줘도됨 )
.defaultSuccessUrl() : 로그인 성공시 이동할 페이지
Password Encode Bean등록
@Bean public BCryptPasswordEncoder encodePassword() { return new BCryptPasswordEncoder(); }
*csrf : Cross site Request forgery로 사이즈간 위조 요청
Spring Security에서 기본적으로 제공 중
이번엔 Session을 이용한 StateFul방식이 아닌 jwt토큰을 이용한 Stateless방식으로 사용하기에 CSRF 위변조를 검증할 필요가 없다. > csrf 기능 사용하지 않음.
*configure 원본코드
protected void configure(HttpSecurity http) throws Exception { this.logger.debug("Using default configure(HttpSecurity). " + "If subclassed this will potentially override subclass configure(HttpSecurity)."); http.authorizeRequests((requests) -> requests.anyRequest().authenticated()); http.formLogin(); http.httpBasic(); }
*HttpSecurity
@Service 사용예제
@Autowired private UserInfoRepository userInfoRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; public String login(UserInfoDto userInfoDto) { UserInfo userInfo = UserInfo. builder() .insUserName(userInfoDto.getInsUserName()) .userPassword( bCryptPasswordEncoder.encode(userInfoDto.getUserPassword())) .userRole("ROLE_USER") .build(); userInfoRepository.save(userInfo); }
@UserInfo
@Getter @AllArgsConstructor @Builder @Entity @Table(name="user_info") public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // 기본키맵핑 private Long idx; private String insUserName; private String userPassword; private String userRole; @CreationTimestamp private Timestamp insDate; }
@UserInfoDto
@Data public class UserInfoDto { private Long idx; private String insUserName; private String userPassword; private String userRole; private Timestamp insDate; }
'기초 > SPRING' 카테고리의 다른 글
[Spring] SpringBoot Security 구글 로그인 (react, nginx) (0) 2022.03.27 [Spring] SpringBoot Security 폼 로그인 (react, nginx) (0) 2022.03.27 [Spring] 기본개념정리 (수정중) (0) 2022.03.23 [Spring] 시큐어 코딩 가이드 (0) 2022.01.03 전자정부 프레임워크 변경사항 (0) 2022.01.03