@AuthenticationPrincipal과 org.springframework.security.core.userdetails.User를 사용하여template page에 user 정보 출력하기
pom.xml수정
thymeleaf-extra를 사용하는 것은 편하긴하지만 오래됐기때문에 새로운 방식으로 재정의해준다.
thymeleaf-extra dependency를 제거하고html에서 타임리프Security적용한 것을 전부 제거해준다.
MemberService.java 수정
@Service
@Slf4j
public class MemberService implements UserDetailsService {
@Autowired
private MemberDao memberDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MemberVO member = this.memberDao.getUserByID(username);
Collection<SimpleGrantedAuthority> roles = new ArrayList<SimpleGrantedAuthority>();
String[] array = member.getRole().split(",");
for (String str : array) roles.add(new SimpleGrantedAuthority(str));
// log.debug("Role : {}", roles.toString());
UserDetails user = new User(username, member.getPasswd(), roles);
return user;
}
}
,을 기준 배열을 만들고 루프를 돌면서 SimpleGrantedAuthority컬랙션에 추가해주는 것 즉 여러개의 권한을 가지고 있는 사용자를 위한 method이다.
Security Controller.java수정
package com.example.security;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import lombok.extern.slf4j.Slf4j;
@Controller
@Slf4j
public class SecurityController {
@GetMapping("/")
public String index() {
log.info("called Index page");
return "index"; //index.html
}
@GetMapping("/member")
public void forMember(@AuthenticationPrincipal User principal, Model model) {
log.info("called Member page user's role = {}", principal.getAuthorities());
}
@GetMapping("/manager")
public void forManager(@AuthenticationPrincipal User principal, Model model) {
log.info("called Manager page");
model.addAttribute("username", principal.getUsername());
model.addAttribute("roles", principal.getAuthorities());
}
@GetMapping("/admin")
public void forAdmin(@AuthenticationPrincipal User principal, Model model) {
log.info("called Admin page");
model.addAttribute("username", principal.getUsername());
model.addAttribute("roles", principal.getAuthorities());
}
@GetMapping("/login")
public void login() {
// login.html
}
@GetMapping("/accessDenied")
public void accessDenied() {
// accessDenied.html
}
@GetMapping("/loginSuccess")
public void loginSuccess(@AuthenticationPrincipal User principal, Model model) {
}
@GetMapping("/logout")
public void logout() {
log.info("called Logout page");
// logout.html
}
}
@AuthenticationPrincipal은 sec NameSpace를 대신하는 Annotation이다.
loginSuccess.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>
<span style="color: red">로그인 인증 성공</span>
</h3>
<h5>
<a th:href="@{/}">Index Page로 이동</a>
</h5>
<div th:each="authority : ${#authentication.principal.authorities}">
<h4 th:if="${#strings.trim(authority)} eq 'ROLE_MEMBER'">
<a th:href="@{/member}">Member Page로 이동</a>
</h4>
<h4 th:if="${#strings.trim(authority)} eq 'ROLE_MANAGER'">
<a th:href="@{/member}">Manager 전용 Page로 이동</a>
</h4>
<h4 th:if="${#strings.trim(authority)} eq 'ROLE_ADMIN'">
<a th:href="@{/admin}">Admin 전용 Page로 이동</a>
</h4>
</div>
</body>
</html>
한객체가 가지고 있는 authority만큼 loop를 돈다.
member.html수정
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Member page : Login 성공한 분만 보입니다.</h1>
<ul th:if="${#authentication.principal.username ne null}">
<li>User name : <span
th:text="${#authentication.principal.username}"></span></li>
<li>Authorities : <span
th:text="${#authentication.principal.authorities}"></span></li>
</ul>
<form th:action="@{/logout}" method="get"
th:if="${#authentication.principal.username ne null}">
<button>Logout</button>
</form>
</body>
</html>
manger.html수정
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Manager page : Manager 권한을 가진 분만 보입니다.</h1>
<ul th:if="${username ne null}">
<li>User name : <span th:text="${username}"></span></li>
<li>Authorities : <span th:text="${roles}"></span></li>
</ul>
<form th:action="@{/logout}" method="get" th:if="${username ne null}">
<button>Logout</button>
</form>
</body>
</html>
member.html처럼 길게 정의하지 되는 이유는 Controller 에 서 이미 정제되서 들어오기 때문이다.
'SpringBoot 코딩' 카테고리의 다른 글
12. Naver, Google을 이용하여 oauth인증하기 (0) | 2021.12.12 |
---|---|
10. DB와 연동한 Security, Password Encording (SpringSecurity) (0) | 2021.12.11 |
9. Spring SeCurity (SpringBootSecurityDemo) (0) | 2021.12.11 |
8. RestFulApi를 이용한 프로젝트만들기, war packaging 진짜 Tomcat사용하기 (demo) (0) | 2021.12.09 |
7.2 Mybatis와 hikariCP를 이용한 프로젝트 만들기(BootJdbcDemo) (0) | 2021.11.26 |