티스토리 뷰

 

스프링시큐리티에서 가장 많이 언급될 단어로는

인증과 인가 비슷한 형태이기 때문에 헷갈릴 수 있으니

아래 개념에서 확실하게 숙지하고 진행하는게 좋다.

 

 인증과 인가

- 인증(Authentication) : 사용자가 맞는지 확인하는 과정
- 인가(Authorization) : 사용자에게 특정한 권한을 부여하는 과정

 

 pom.xml 설정(스프링시큐리티 관련)

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
</dependency>

 

 스프링시큐리티 태그 라이브러리 선언

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authorize access="isAuthenticated()">
<sec:authentication property="principal" var="user"/>
	<c:if test="${user.권한 eq '관리자'}">
		...인증되고 인가된 사용자에게 표출할 영역
	</c:if>
</sec:authorize>
스프링시큐리티에서 제공하는 기능을 jsp에서 태그로 사용할 수 있음.
 

● 스프링시큐리티 설정

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
UsrService usrService; //회원 관련 로직을 담당하고있는 Service(사용자마다 생성되는 클래스명은 다름)
@Autowired
private DataSource dataSource; //DB관련 설정 (사용자마다 생성되는 클래스명은 다름)
@Bean //비밀번호 암호화 관련
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
   
@Override
protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests() /*인가 설정*/
        .antMatchers("/admin/**").hasAuthority("ADMIN")
            .antMatchers("/", "/usr/join", "/resources/**", "/docs/**").permitAll() //모든 권한 인가 허용
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/usr/login") //로그인 페이지 URL
            .defaultSuccessUrl("/usr/loginSuccess")
            .loginProcessingUrl("/usr/login")
            .usernameParameter("usrId")
            .passwordParameter("usrPw")
            .permitAll()
            .and()
        .logout()
        .logoutUrl("/usr/logout")
        .logoutSuccessUrl("/")
        .invalidateHttpSession(true)
        .permitAll();
       
}
   
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //인증 시 비밀번호 암호화 설정
    auth.userDetailsService(usrService).passwordEncoder(passwordEncoder());
   
    }   
}

 

@Configuration
@EnableWebSecurity

java configuration class스프링시큐리티 관련 설정을 위해

WebSecurityConfigurerAdapter 클래스를 상속 받은 후
필수적인 중요한 설정 두가지를 override를 해야한다.
eclipse 내에 서는 ctrl + space 를 자동완성 기능이 있기때문에 보다 override 하고자하는
메소드를 입력하기 편리하다.

 

자동완성 표출목록

메소드 1. configure(HttpSecurity http)

  • 스프링시큐리티에서 제공하는 로그인폼 사용 여부
  • 특정 URL(resource 경로)에 대한 접속 허용 여부
  • 특정 권한에 대한 접속 허용 여부
  • 로그아웃 URL 설정 
메소드2. configure(AuthenticationManagerBuilder auth)
스프링시큐리티 인증 관련 설정을 하는 영역으로
설정방법에는
- DB에서 조회하는 방법 (jdbcAuthentication)
- LDAP 기반 인증 방법 (ldapAuthentication)
- 직접 설정하는 방법 (userDetailsService)

등이 있으나 필자는 UserDetailsService 인터페이스를 구현하여 직접 적용해보았다.

auth.userDetailsService()를 사용한다면

userDetailsService 인터페이스를 구현한 클래스에 

loadUserByUsername 메소드를 override 하여 인증 로직을 작성해 줘야 한다.

필자는 UserService 클래스에 구현하였다.

구현은 다음 단락에 설명되어있다.

 

 UserDetailsService 구현
 
@Service
@Transactional
public class UsrService implements UserDetailsService  {
...
...
	@Override
	public UserDetails loadUserByUsername(String usrId) throws UsernameNotFoundException {
		
        Optional<UsrEntity> userEntityWrapper = usrRepository.findByUsrId(usrId);
        UsrEntity userEntity = userEntityWrapper.get();
        List<GrantedAuthority> authorities = new ArrayList<>();
        RoleUsrEntity roleUsrEntity = userEntity.getRole();
        String authRoleCd = roleUsrEntity.getRoleCd();
        
        if(userEntity.getRole() != null) {
        	authorities.add(new SimpleGrantedAuthority(authRoleCd));
        } else {
        	authorities.add(new SimpleGrantedAuthority("R01"));
        }
        return new User(userEntity.getUsrId(), userEntity.getUsrPw(), authorities);
    }
}

필자는 회원 가입할 때 회원정보 중 비밀번호를 BCryptPasswordEncoder 암호화하여 저장하였음.

암호화된 비밀번호는 절대 복호화될 수 없는 점을 숙지.

loadUserByUsername 메소드에서는 로그인 시도한 사용자의 ID를 조회하여 권한과 비밀번호를 리턴하고

passwordEncoder를 이용하여 입력한 비밀번호를 암호화한 값과 조회된 암호화된 비밀번호를

비교하여 일치한 경우 인증에 성공시킨다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함