0. 컨트롤러의 메서드에서 Authentication 객체 받기
요청을 받아 처리하는 컨트로러 메서드들은 Authentication 객체를 파라미터로 받을 수 있다. 이 Authentication 객체를 사용하여 사용자의 간단한 정보를 확인하거나 getPrincipal() 메서드를 통해 로그인 처리에 사용했던 UserDetails의 구현 클래스를 반환받을 수 있다.
@GetMapping("/test")
public String test(Authentication auth) {
// 사용자 아이디
String memId = auth.getName();
// 로그인에 사용했던 UserDetails의 구현 클래스로 변환
AuthUser user = (AuthUser) auth.getPrincipal();
MemberVO memVO = user.getMemVO();
...
}
* UserDetails의 구현 클래스 (User 클래스를 상속)
package com.java.web.member.service;
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import com.java.web.vo.MemberVO;
public class AuthUser extends User {
private static final long serialVersionUID = 1L;
private MemberVO memVO;
public AuthUser(String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public AuthUser(MemberVO memVO) {
super(memVO.getMemId(), memVO.getMemPass(),
memVO.getAuthList().stream()
.map(auth -> new SimpleGrantedAuthority(auth.getAuth()))
.collect(Collectors.toList()));
this.memVO = memVO;
}
public MemberVO getMemVO() {
return memVO;
}
public void setMemVO(MemberVO memVO) {
this.memVO = memVO;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
1. SecurityContextHolder 클래스로 Authentication 객체 반환받기
컨트롤러 메서드의 파라미터를 사용하지 않고, 바로 SecurityContextHolder 클래스를 사용해 Authentication 객체를 반환받는 것도 가능하다.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
'Java > Spring Framework' 카테고리의 다른 글
[Spring Framework] 스프링 시큐리티 다중 로그인 화면 (0) | 2023.02.23 |
---|---|
[Spring Framework] 스프링 시큐리티에서 동시 접속 제한하기 (0) | 2023.02.17 |
[Spring Framework] 어노테이션을 사용한 시큐리티 지정 (0) | 2023.02.15 |
[Spring Framework] 시큐리티 설정 정리 (0) | 2023.02.15 |
[Spring Framework] 스프링 시큐리티 자동 로그인 (0) | 2023.02.14 |