79일 차 - 스프링 Security tag 라이브러리 (23.04.20)

yvonne·2023년 4월 20일
0

📂Spring

목록 보기
11/18
post-thumbnail

📝 security tag 라이브러리

  • Principal: username 아이디
    • UserDetailsService에서 리턴한 객체
    • 객체는 UserDetails 타입
  • Credentials: password 비밀번호
  • Authorities: 권한

✔ LoginController.java

package edu.global.ex.controller;

import java.security.Principal;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class LoginController {

	@GetMapping("/login")
	public String login() {
		log.info("login() ..");
		return "login/login";
	}

	@RequestMapping(value = "/loginInfo", method = RequestMethod.GET)
	public String loginInfo(Authentication authentication, Principal principal, Model model) {

		String user_id;

		// 1.SpringContextHolder를 통하여 가져오는 방법(일반적인 빈에서 사용 할수있음 )
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		user_id = auth.getName();
		System.out.println("유저 아이디:" + user_id);

		// 2.authentication 객체로 가져오는 방법(많은 )
		System.out.println("authentication 유저 아이디:" + authentication.getName());
		System.out.println("authentication 권한들:" + authentication.getAuthorities());

		// 3.Principal 객체로 가져오는 방법(가져올수 있는게 getName() 정도
		System.out.println("Principal 유저 아이디:" + principal.getName());

		return "redirect:/";
	}
}

✔ home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> 
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <title>메이페이지</title>
</head>

<body>

<h1>메인페이지</h1>

<sec:authorize access="isAnonymous()"> <!-- 익명의 유저일 때  -->
   <p><a href="<c:url value="/login/loginForm" />">로그인</a></p>
</sec:authorize>

<sec:authorize access="isAuthenticated()"> <!--  로그인된 유저일 때 -->
   <form:form action="${pageContext.request.contextPath}/logout" method="POST">
       <input type="submit" value="로그아웃" />
   </form:form>
   <p><a href="<c:url value="/loginInfo" />">로그인 정보 확인 방법3 가지</a></p>
    <p>principal: <sec:authentication property="principal"/></p>  <!--  authentication 객체의 getPrincipal() 불러온다는 의미  -->
     <p><sec:authentication property="principal.username"/>님 환영합니다.</p> <!-- UserDetailsVO.java의 getUsername() 불러온다는 의미 -->
    
   <sec:authorize access="hasRole('ADMIN')">
        <p>당신은 관리자 입니다.</p>
   </sec:authorize>
  
   <sec:authorize access="hasRole('USER')">
        당신은 일반 유저 입니다.
   </sec:authorize>
        
</sec:authorize>

<h3>
    [<a href="<c:url value="/add/addForm" />">회원가입</a>]
    [<a href="<c:url value="/user/userHome" />">유저 홈</a>]
    [<a href="<c:url value="/admin/adminHome" />">관리자 홈</a>]
</h3>
</body>
</html>

  • 결과
    🔎 User 로그인 시

    🔎 Admin 로그인 시

profile
개발 연습장

0개의 댓글