Spring Security 권한관련 [펌]
권한
현재 정의 된 사용자 권한은 아래와 같다.
ROLE_USER (회원)
ROLE_USER_VERIFIED (인증된 회원)
ROLE_USER_NON_VERIFIED (인증되지 않은 회원)
ROLE_ADMIN (관리자)
로그인을 한 회원은 기본적으로 ROLE_USER 권한을 가지고 있고, 기타 회원에 해당하는 권한을 중복으로 가지게 된다.
//예) 인증이 완료된 회원
ROLE_USER, ROLE_USER_VERIFIED
@Secured Annotation 을 이용한 권한 체크
기본적으로는 모든 사용자가 모든기능에 접근 가능하고, 기능별로 권한체크를 하여 사용을 제한한다. 이를위해 @Secured Annotation 을 이용하여 권한은 제한한다. @Secured 는 Spring에서 생성된 Bean에서 사용가능하고, Class와 Method 모두 에서 설정 가능하다. Website 를 위한 권한은 보통 Controller 또는 Controller의 Method 에 설정한다.
// Controller Class의 전역설정
@Controller
@Secured("ROLE_USER")
@RequestMapping(value="/sample")
public class SampleController extends BasicLayoutController {
...
}
Method 에서 체크할 경우.
// 로그인 여부 체크
@Secured("ROLE_USER")
@RequestMapping(value = "/{categoryId}/create", method = RequestMethod.DELETE)
public String create() {
...
}
여려 권한 체크도 가능하다.
// 회원과 관리자 모두에게 제공
@Secured({"ROLE_USER", "ROLE_ADMIN"})
@RequestMapping(value = "/{categoryId}/create", method = RequestMethod.DELETE)
public String create() {
...
}
로그인 여부 체크를 위해서는 ROLE_USER가 있는지를 체크하면 된다.
JSTL 을 이용한 권한 체크
JSP 에서 권한에 따른 View Handling 을 위해서는 Spring Security 에서 제공하는 TagLib 을 이용한다.
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<ul class="nav navbar-nav navbar-right">
<!-- 회원 권한이 없을 때 -->
<sec:authorize ifNotGranted="ROLE_USER">
<li><a href="/user/sign_up">회원가입</a></li>
<li><a href="/user/login">로그인</a></li>
</sec:authorize>
<!-- 회원 권한이 있을 때 -->
<sec:authorize ifAnyGranted="ROLE_USER">
<li><a href="/user/logout">로그아웃</a></li>
</sec:authorize>
<!-- 여러 권한 체크 -->
<sec:authorize ifAnyGranted="ROLE_USER, ROLE_ADMIN">
<li><a href="/user/edit">정보수정</a></li>
</sec:authorize>
</ul>
로그인 세션 객체
Spring Security를 이용하면 Authentication Bean 이 생성된다. 이를 Controller 에서 주입 받거나, JSP 에서 JSTL Tag 를 이용하여 접근 할 수 있다.
로그인 한 사용자의 정보는 net.okjsp.user.model.User의 instance 객체로 저장되며, Authentication에 principal property 로 저장 된다.
Controller를 통한 Authentication 객체 접근
@Secured("ROLE_USER")
@RequestMapping(value = "/{categoryId}/create", method = RequestMethod.POST)
public String create(
Sample sample,
Authentication authentication) { // Authentication 를 주입 받음
User user = (User) authentication.getPrincipal(); // Authentication 저장된 principal 객체를 User 객체로 Cast
sample.setWriteId(user.getUserId()); // User 객체를 이용한 로그인 회원 정보 접근
sampleBoardService.create(sample);
return "redirect:/sample/"+categoryId;
}
JSTL Tag 를 통한 Authentication 객체 접근
위해서는 Spring Security 에서 제공하는 TagLib 을 이용하면 authentication Tag 를 통하여 Authentication Bean 에 접근 가능하다.
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication var="user" property="principal" />
${user.nickName} (${user.loginId}) 님! 안녕하세요.