이전에 전통적인 로그인 방법인 세션으로 로그인 요청하던 관련 코드는 주석처리를 하고 

[UserApiController]

@PostMapping("/api/user/login")
public ResponseDto<Integer> login(@RequestBody User user, HttpSession session){
    System.out.println("UserApiController : login 호출됨");
    User principal = userService.로그인(user); 

    if(principal != null) {
        session.setAttribute("principal", principal);   // session.setAttribute(String key, object value)
    }
    return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);  // 1이면 로그인 정상적 요청됨
}

 

 

 

스프링 시큐리티를 통해 principal 로 로그인 해보기

 

 

- 시큐리티 라이브러리

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 

시큐리티 라이브러리가 설치가 되면 페이지 이동을 할때 시큐리티가 가로채서 로그인 화면으로 가게된다. (권한제한)

세션은 자동으로 생성

 

 

* 로그인화면과 로그아웃화면은 시큐리티가 정해줌

http://localhost:8000/login

 

아이디는 user, 비밀번호는 콘솔창에 있다. 

시큐리티 비밀번호

 

 

이전에 세션 유무로 네브바를 다르게 보이도록 했던 <c:when test="${empty sessionScope.principal}"> 이제 쓰지 않고

시큐리티 태그lib 를 사용한다

 

 

시큐리티 태그 사용법 

 

시큐리티 태그 라이브러리 설치 

<!-- 시큐리티 태그 라이브러리 -->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-taglibs</artifactId>
</dependency>

 

 

태그 lib는 header.jsp 상단에 위치시키고 시큐리티 태그 넣기 ( security taglib을 사용하고 싶은 jsp 파일 상단에 선언.)

태그 lib 은 https://www.baeldung.com/spring-security-taglibs 사이트에서 가져옴.

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

<sec:authorize access="isAuthenticated()">
   <sec:authentication property="principal" var="principal"/>
</sec:authorize>

 

 

[header.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="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authorize access="isAuthenticated()">
	<sec:authentication property="principal" var="principal"/>
</sec:authorize>

<!DOCTYPE html>
...

 

 

 

security tag는 authentication, authorize, accesscontrollist  이렇게 3가지가 있다.

 

**참고 http://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html 

  • ExpressionDescription
hasRole([role]) Returns true if the current principal has the specified role.
hasAnyRole([role1,role2]) Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings)
principal Allows direct access to the principal object representing the current user
authentication Allows direct access to the current Authentication object obtained from the SecurityContext
permitAll Always evaluates to true
denyAll Always evaluates to false
isAnonymous() Returns true if the current principal is an anonymous user
isRememberMe() Returns true if the current principal is a remember-me user
isAuthenticated() Returns true if the user is not anonymous
isFullyAuthenticated() Returns true if the user is not an anonymous or a remember-me u

 

 

Authentication(인증)은 로그인 자격 증명을 확인하여 로그인 한 사용자를 인식하는 것이며,

Authorization(권한 부여)는 액세스 제어로 사용자가 읽기, 수정, 삭제를 허용하는지 여부를 확인하는 것입니다. 

권한 부여는 사용자의 신원이 성공적으로 인증 된 후에 발생합니다

 

<sec:authorize access="isAuthenticated()">
   <sec:authentication property="principal" var="principal"/>
</sec:authorize>

<sec:authorize access="isAuthenticated()"> : 인증(로그인)이 됐는지 아닌지 확인하고 권한부여

     <sec:authentication property="principal" var="principal"/>  : 인증된 사용자 정보(principal)를 가져와서

                                                                                                        var="변수" 에 담는다.

 

 

principal 이란?  Allows direct access to the principal object representing the current user

현재 유저의 object에 직접적으로 접근할 수있도록 허용해준다~

 

 

 

로그인을 하면 세션이 자동 생성하고 세션은 pricipal 에 저장을 한다. 따라서 security에서 인증된 사용자 정보는 principal​에 저장

 

 

property="principal" var="principal"

해당페이지에서 사용할 수 있는 변수라서 그 변수를 가지고

<c:choose>
    <c:when test="${empty principal}">  <!-- "$ 띄어쓰기 하면 절대안됨 -->
        <ul class="navbar-nav">
            <li class="nav-item"><a class="nav-link" href="/loginForm">로그인</a></li>
            <li class="nav-item"><a class="nav-link" href="/joinForm">회원가입</a></li>
        </ul>
    </c:when>
    <c:otherwise>
    ...

<c:when test="${empty sessionScope.principal}"> 와 똑같이 

<c:when test="${empty principal}">  'principal 변수가 있으면 혹은 없으면' 을 가정하여 네브바를 바꿀 수 있다.

 

 

 

 

* principal이 무얼 들고있는지 궁금해서 <h1>${principal}</h2> 로 보자면

org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[]]

 

 

시큐리티 과정을 다시 말해

시큐리티 라이브러리를 설정한 프로젝트를 시작할시 기본적으로 잠겨버리고

username을 기본 제공하고 콘솔창에 나온 비번으로 로그인을하면

스프링이 세션을 자동생성하여 저장하고 세션은 principal 에 저장하게 된다.

security tag인 authentication, authorize 를 이용하여 principal 을 통해 로그인을 하면 된다!

 

 

 

 

 

반응형
LIST

+ Recent posts