Spring 4/<sec:authorize>
Spring authorize tag example
Soul-Learner
2016. 11. 10. 12:34
스프링 Security 의 인증정보를 콘트롤러 클래스와 뷰(JSP)에서 사용하는 예
Spring Security 를 이용하여 게시판의 글 작성자만 자신의 글을 삭제할 수 있도록 하는 예
Board 객체에 게시판 글이 저장되어 request 영역에 board 란 이름으로 저장된 경우
JSP 에서 다음과 같이 글 작성자에게만 [글 삭제] 버튼이 보여지게 할 수 있다
<sec:authentication property="name" var="secName"/> <sec:authorize access="${secName==board.writer}"> <button type="button" onclick="deleteBoard();">글 삭제</button> </sec:authorize>
위의 access 속성에 주로 사용되는 값들은 다음과 같은 것들이 있다
isAnonymous()
isAuthenticated()
hasRole('ROLE_ADMIN')
hasRole('ROLE_USER') and isAuthenticated()
hasAnyRole('ROLE_MEMBER', 'ROLE_ADMIN')
permitAll
스프링 콘트롤러 클래스에서 스프링 Security 인증정보에 접근하는 예
@RequestMapping(value = "/authTest", method = RequestMethod.GET) public String authTest( Model model, Authentication auth) { UserDetailsVO vo = (UserDetailsVO) auth.getPrincipal(); String name = auth.getName(); boolean ok = auth.isAuthenticated(); model.addAttribute("id", name); model.addAttribute("login", ok); return "authTest"; }
JSP에서 스프링 Security 의 인증정보에 접근하는 예
<%@page import="java.security.Principal"%> <%@page import="org.springframework.security.core.GrantedAuthority"%> <%@page import="java.util.List"%> <%@page import="org.springframework.security.core.Authentication"%> <%@page import="org.springframework.security.core.context.SecurityContext"%> <%@page import="java.util.Enumeration"%> <%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> <% Object ctxObj = session.getAttribute("SPRING_SECURITY_CONTEXT"); SecurityContext ctx = (SecurityContext) ctxObj; Authentication auth = ctx.getAuthentication(); List<GrantedAuthority> roles = (List<GrantedAuthority>)auth.getAuthorities(); Object detObj = auth.getDetails(); String name = auth.getName(); boolean isAuth = auth.isAuthenticated(); System.out.println("roles:"+roles); System.out.println("detObj:"+detObj); System.out.println("name:"+name); System.out.println("isAuth:"+isAuth); %>