※ 보유권한에 따른 페이지 이동
1. access-denied-handler 지정 (security-context.xml)
<security:access-denied-handler ref="webAccessDeniedHandler" />
2. AccessDeniedHandler 클래스 구현 (Service)
package com.brainz.ja.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;
import com.brainz.ja.vo.UserDetailsVo;
import com.brainz.ja.vo.UserVo;
@Service("webAccessDeniedHandler")
public class WebAccessDeniedHandler implements AccessDeniedHandler {
private static final Logger logger = LoggerFactory.getLogger(WebAccessDeniedHandler.class);
@Override
public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException ade)
throws IOException, ServletException {
res.setStatus(HttpStatus.FORBIDDEN.value());
String requestUri = req.getRequestURI();
if(ade instanceof AccessDeniedException) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && requestUri.equals("/ja/user/registerUser") &&
((UserDetailsVo) authentication.getPrincipal()).getAuthorities().contains(new SimpleGrantedAuthority("ROLE_USER")))
{
req.setAttribute("msg", "접근권한 없는 사용자입니다.");
req.setAttribute("nextPage", "../user/mainPage");
} else {
req.setAttribute("msg", "(로그인 상태) 로그아웃 되었습니다.");
req.setAttribute("nextPage", "../user/mainPage");
res.setStatus(HttpStatus.UNAUTHORIZED.value());
SecurityContextHolder.clearContext();
}
} else {
logger.info(ade.getClass().getCanonicalName());
}
req.getRequestDispatcher("/login/deniedPage").forward(req, res);
}
}
3. 컨트롤러 작성
@RequestMapping("deniedPage")
public String accessDenied(){
return "login/deniedPage";
4. view페이지 작성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Denied-Page</title>
</head>
<body>
<script type="text/javascript">
alert("${msg}");
window.location.href = "${nextPage}";
</script>
</body>
</html>
'수업 내용 > 기업 프로젝트 (D조)' 카테고리의 다른 글
스프링 시큐어리티 (0) | 2022.04.11 |
---|---|
(103일차) 3월 24일 (0) | 2022.03.24 |
(95일차) 3월 14일 (0) | 2022.03.14 |
(94일차) 3월 11일 (0) | 2022.03.11 |
(93일차) 3월 10일 (0) | 2022.03.10 |