본문 바로가기
Spring/study

스프링 시큐리티 사용자 정보 가져오기

by avvin 2019. 8. 13.



출처 : https://otrodevym.tistory.com/entry/Spring-Security%EC%97%90%EC%84%9C-%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EB%B3%B4-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0



1. JSP 페이지


home.jsp
<%@ taglib prefix="sec"
    uri="http://www.springframework.org/security/tags"%>

            <td><sec:authorize access="isAuthenticated()">
                    <sec:authentication property="principal.username" var="user_id" />
                    <div id="user_id">안녕하세요. ${user_id }</div>
                </sec:authorize></td>


<input type="hidden" value="${user_id}">

2. SpringContextHolder 

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        String user_id = auth.getName();



3. Contoller

    @RequestMapping("/")
public String test(Principal principal) {

String user_id = principal.getName();

}


4. User 클래스로 변환

User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

String user_id = user.getUsername();


 



출처: https://otrodevym.tistory.com/entry/Spring-Security에서-사용자-정보-가져오기 [미니 블로그 : 메모하는 습관]





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    //글 등록 (dao : 글 삽입 )
    @RequestMapping("insert.do")
    public String insert(@ModelAttribute BoardDTO dto, HttpSession session)
        throws Exception {
        // 시큐리티컨텍스트홀더 객체에서 사용자아이디를 가져옴★
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails)principal;
        
        String id = userDetails.getUsername();
 
        dto.setId(id); 
        //레코드 저장
        boardService.create(dto);
        //게시물 목록으로 이동
        return "redirect:/board/list.do";
    }