쉬운 프로그래밍

[Spring Boot] Spring Security Security Config 본문

Programming/Spring Boot

[Spring Boot] Spring Security Security Config

쉬운형 2021. 2. 2. 16:55
package com.mkl.book.config.auth;

import com.mkl.book.user.domain.Role;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final CustomOAuth2UserService customOAuth2UserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        	.csrf().disable()
                .headers().frameOptions().disable()
                .and()
                	.authorizeRequests()
                	.antMatchers("/", "/css/**", "/images/**", "/js/**")
                    	.permitAll()
                	.antMatchers("api/v1/**")
                    	.hasRole(Role.USER.name())
                	.anyRequest().authenticated()
            .and()
                .logout()
                    .logoutSuccessUrl("/")
            .and()
                .oauth2Login()
                    .userInfoEndpoint()
                        .userService(customOAuth2UserService);
    }
}

* @EnableWebSecurity : Spring Securiry 설정 활성화

 

* authorizeRequests 

    - URL별 권한 관리를 설정하는 옵션의 시작점

    - authorizeRequests가 선언되어야만 antMatchers 옵션 활성화 가능

 

* antMatchers

    - 권한 관리 대상 옵션 지정

    - URL / HTTP 메소드별로 지정 가능

    - 위에서는 "/" 등 지정된 URL은 permitAll() 옵션을 통해 전체 열람 가능

    - api/... URL은 USER ROLE을 가진 사람만 열람 가능하도록함

 

* anyRequest

    - 설정한 값 외에 나머지 URL 나타냄

    - 위에서는 authenticated()를 통해 로그인 한 사용자만 접속 가능하도록함

   

* logout().logoutSuccessUrl("/")

    - 로그아웃 성공시 "/" 주소로 이동함

 

* oauth2Login

    - OAuth 2.0 로그인 기능에 대한 여러 설정의 진입점

 

* userInfoEndpoint

    - OAuth 2.0 로그인 성공 이후 사용자 정보를 가져올 때의 설정들을 담당함

 

* userService

    - 소셜 로그인 성공 시 후속 조치를 진행할 UserService 인터페이스의 구현체 등록

    - 소셜 서비스에서 사용자 정보를 가져온 상태에서 추가로 진행하고자 하는 기능 명시 가능

 

 

추가

 

 .and() 
          .formLogin()
            .loginPage("/login") 
            .defaultSuccessUrl("/") 

* loginPage -> 로그인 페이지 설정

 

* defaultSuccessURL -> 로그인 성공 후 리다이렉트 주소

 

 

 

Comments