Spring Security를 이용하여 사용자 세부 정보를 검색할 수 있다
Get the User in a Bean
The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder
현재 인증된 보안 principal 값을 가져오려면 SecurityContextHolder 를 호출한다
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
return currentUserName;
}
액세스 시도 전에 인증된 사용자의 여부를 확인하여 접근한다
하지만 이러한 static 호출보다 좋은 방법들이 있다.
Get the User in a Controller
We have additional options in a @Controller annotated bean.
We can define the principal directly as a method argument, and it will be correctly resolved by the framework:
@Controller 애노테이션 빈을 추가한 경우
principal 메서드 인수로 직접 정의하여 값을 받아올 수 있다
@Controller
public class SecurityController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}
}
authentication token도 사용 가능하다
@Controller
public class SecurityController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Authentication authentication) {
return authentication.getName();
}
}
The API of the Authentication class is very open so that the framework remains as flexible as possible.
Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:
API 로 값을 유지하기 위해서는 UserDetails 인스턴스로 캐스팅해준다
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());
HTTP 요청 시
@Controller
public class GetUserWithHTTPServletRequestController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}
Get the User via a Custom Interface
Spring DI를 최대한 활용하여 @Controller 뿐 아닌 모든 곳에서 인증을 하기 위한 코드이다
public interface IAuthenticationFacade {
Authentication getAuthentication();
}
@Component
public class AuthenticationFacade implements IAuthenticationFacade {
@Override
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
}
facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable:
@Controller
public class GetUserWithCustomInterfaceController {
@Autowired
private IAuthenticationFacade authenticationFacade;
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple() {
Authentication authentication = authenticationFacade.getAuthentication();
return authentication.getName();
}
}
Get the User in JSP
The currently authenticated principal can also be accessed in JSP pages, by leveraging the Spring Security Taglib support.
First, we need to define the tag in the page:
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
Next, we can refer to the principal:
<security:authorize access="isAuthenticated()">
authenticated as <security:authentication property="principal.username" />
</security:authorize>
Get the User in Thymeleaf
we can refer to the principal in the HTML page using the sec:authorize attribute:
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div sec:authorize="isAuthenticated()">
Authenticated as <span sec:authentication="name"></span></div>
</body>
</html>
'Spring 정리ver2 > Security' 카테고리의 다른 글
[baeldung] Find the Registered Spring Security Filters (0) | 2023.04.27 |
---|---|
[baeldung] Default Password Encoder in Spring Security 5 (0) | 2023.04.27 |
[baeldung] Control the Session with Spring Security (0) | 2023.04.26 |
[baeldung] Intro to Spring Security Expressions (0) | 2023.04.26 |