티스토리 뷰

 
어제 포스팅을 마무리 하지 못해서 오늘 오전에 짬내서 마무리하고 올렸었습니다. 어제 1일1포스팅을 못지켰으므로 오늘 2포스팅을 진행합니다.
이번에는 Spring Security의 기타 기능들에 대해서 살펴보겠습니다.

우선 살펴볼 기능은 Authority 별 접근 권한 설정입니다.
특정 계정의 경우 USER와 ADMIN 두개로 설정을 했었는데요. ADMIN만 접근 가능한 페이지, USER만 접근 가능한 페이지를 설정해보겠습니다.
1. 해당 테스트용 페이지를 만들기 위해서 HomeController에 admin/user Path를 추가해줍니다.
package com.cusonar.example.home.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cusonar.example.home.domain.Home;
import com.cusonar.example.home.mapper.HomeMapper;

@RestController
public class HomeController {
     @Autowired HomeMapper homeMapper;
    
     @RequestMapping("/")
     public String home() {
          return "Hello World!";
     }
    
     @RequestMapping("/{name}")
     public Home home(@PathVariable String name) {
          Home home = homeMapper .readHome(name);         
          return home ;
     }
    
     @RequestMapping("/admin")
     public String admin() {
          return "This is admin page";
     }
    
     @RequestMapping("/user")
     public String user() {
          return "this is user page";
     }
}

 
2. SecurityConfig에서 권한 설정을 해줍니다.
package com.cusonar.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.cusonar.example.user.service.UserService;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
     @Autowired UserService userService;
    
     @Override
     protected void configure(HttpSecurity http) throws Exception {
          http
               .csrf().disable()
               .authorizeRequests()
                    .antMatchers("/user").hasAuthority("USER")
                    .antMatchers("/admin").hasAuthority("ADMIN")
                    .anyRequest().authenticated()
                    .and()
               .formLogin()
                    .and()
               .logout()
               ;
     }
    
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userService)
               .passwordEncoder(userService.passwordEncoder())
               ;
     }
}
     . antMatchers의 파라미터로 경로를 지정해줍니다. 경로에는 **, * 과 같은 패턴을 사용할 수 있습니다.
     . 뒤에 hasAuthority의 파라미터로 지정해준 권한을 입력해줍니다. 
     . 테스트를 위해 logout() 기능도 추가해줍니다.

3. 테스트를 아래와 같이 진행해보시면 됩니다. (cusonar의 패스워드가 인코딩되어서 입력되어 있다고 가정합니다.)
     a. http://localhost:8080/으로 접속합니다. user1/pass1 으로 접속합니다.
     b. http://localhost:8080/user로 접속합니다. 페이지가 정상적으로 나오는지 확인합니다.
     c. http://localhost:8080/admin로 접속합니다. Access Denied가 뜨는걸 확인할 수 있습니다.
     d. http://localhost:8080/logout을 통해 logout을 진행합니다.
     e. cusonar/1234로 접속을 합니다.
     f. http://localhost:8080/user와 http://localhost:8080/admin 페이지 둘 모두 접속이 되는것을 확인합니다.

4. 이렇게 간단하게 권한별 페이지 접속 관리에 대해서 확인했습니다.

그 외 많이 사용할만한 기능으로는 아래와 같은 것들이 있을것 같습니다.
1. formLogin() 추가 메소드(뒤에 . 찍고 아래 메소드 사용하시면 됩니다.)
     a. successHandler : Login 성공시 추가 작업을 정의합니다. 솔루션의 추가 인증이 필요한 경우 사용할 수 있습니다. SimpleUrlAuthenticationSuccessHandler 클래스를 extends 하거나 AuthenticationSuccessHandler를 구현해서 @Component로 정의한 후 autowired 해서 넣어주시면 됩니다.
     b. failureHandler : Login 실패시 추가 작업을 정의할 수 있습니다. 패스워드 몇회 이상 오류 시 계정 잠금 기능을 사용할 수 있습니다. SimpleUrlAuthenticationFailureHandler 클래스를 extends 하거나 AuthenticationFailureHandler를 구현해서 사용하시면 됩니다.
2. logout() 추가 메소드
     a. logoutSuccessHandler : Logout 성공시 추가 작업을 정의합니다. 1.a에서 솔루션 인증을 추가한 경우, 솔루션 Logout 처리를 해주면 좋을것 같습니다. 마찬가지로 SimpleUrlLogoutSuccessHandler 클래스를 extends 하거나 LogoutSuccessHandler를 구현해서 사용하시면 됩니다.

3. 만약 Login Logic을 아예 변경하고 싶으시면 AuthenticationProvider 인터페이스를 구현해서 사용하면 됩니다.


많은 기능들이 더 있지만 일일이 설명하진 않겠습니다. 사용법은 대부분 API 문서를 보시면 다들 아실수 있으리라 생각합니다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함