본문 바로가기
Java/Spring

[security] 정리

by java개발자 2021. 5. 6.

[코드로 배우는 스프링부트] - 구멍가게 코딩단

1. id/pw로 로그인

1. security lib 추가

2. config 추가

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

3. passwordEncoder 추가

@Bean
PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
}

4-1. 직접 [인증] 매니저 설정

@Override
ptected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication()
    .withUser("user1") // 사용자 계정은 user1
    .password("$2a$10$qbTVRGiC8RePIsMz4z/QP.LjBmLOMGXBCkmW2comzfNaoeidd5/aa") // 1111 패스워드 인코딩
    .roles("USER");
  
  // 또는 서비스로
  auth.userDetailsService(clubUserDetailsService);
  auth.eraseCredentials(false);
}

4-2. 또는 service로

@Service
@RequiredArgsConstructor
public class ClubOAuth2UserDetailsService extends DefaultOAuth2UserService {
    private final ClubMemberRepository repository;
    private final PasswordEncoder passwordEncoder;
    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {

5. [인가]

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests()
  .antMatchers("/sample/all").permitAll()
  .antMatchers("/sample/member").hasRole("USER");
}

 

2. oauth google

1. application-oauth.properties

2. SecurityConfig

@Override
protected void configure(HttpSecurity http) throws Exception {
  //...
  http.oauth2Login() // 추가: oauth로 로그인하기
  .successHandler(successHandler()) // 추가: oauth 로그인 이후 처리
}

@Bean
public ClubLoginSuccessHandler successHandler() {
  return new ClubLoginSuccessHandler(passwordEncoder());
}

3. 서비스

@Service
@RequiredArgsConstructor
public class ClubOAuth2UserDetailsService extends DefaultOAuth2UserService {
  private final ClubMemberRepository repository;
  private final PasswordEncoder passwordEncoder;
  @Override
  public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {

4. 로그인 성공 후 핸들러

public class ClubLoginSuccessHandler implements AuthenticationSuccessHandler {
  private RedirectStrategy redirectStratgy = new DefaultRedirectStrategy();
  private PasswordEncoder passwordEncoder;
  public ClubLoginSuccessHandler(PasswordEncoder passwordEncoder) {
    this.passwordEncoder = passwordEncoder;
  }
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    Authentication authentication) throws IOException, ServletException {

 

*최종 DTO

// User는 id/pw에서 사용

// OAuth2User는 OAuth에서

public class ClubAuthMemberDTO extends User implements OAuth2User {