카테고리 없음

[Spring] Spring Security를 JSP에서 사용하기

미니시리 2024. 8. 18. 23:00

pom.xml 설정

<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
	<version>5.1.5.RELEASE</version>
</dependency>

 

JSP에서 로그인 한 사용자 정보 보여주기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
  <h1>User Detail Page</h1>
  <p>principal: <sec:authentication property="principal"/></p>
  <p>user: <sec:authentication property="principal.user"/></p>
  <p>email: <sec:authentication property="principal.user.email"/></p>
  <p>role: <sec:authentication property="principal.user.role"/></p>
  <p>username: <sec:authentication property="principal.username"/></p>
  <a href="/user/logout">Logout</a>
</body>
</html>

 

Spring Security 표현식

  • hasRole([role]) / hasAuthority([authority]) -> 해당 권한이 있으면 true
  • hasAnyRole([role1, role2]) / hasAuthority([authority]) -> 여러 권한들 중에 하나라도 해당되는 권한이 있으면 true
  • principal -> 현재 사용자 정보를 의미
  • permitAll -> 모든 사용자에게 허용
  • denyAll -> 모든 사용자에게 거부
  • isAnonymous() -> 익명의 사용자 (로그인 하지 않은 경우)
  • isAuthenticated() -> 인증된 사용자
  • isFullyAuthenticated() -> Remember-me로 인증된 것이 아닌 인증된 사용자

 

security-context.xml 파일의 일부

<security:http auto-config="true">
	<security:intercept-url pattern="/user/join" access="permitAll" />
	<security:intercept-url pattern="/user/login" access="permitAll" />
	<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
	<security:intercept-url pattern="/user/**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
	<security:form-login login-page="/user/login" login-processing-url="/user/login" 
		username-parameter="email" password-parameter="password" />
	<security:access-denied-handler ref="customAccessDenied" />
	<security:remember-me data-source-ref="dataSource" token-validity-seconds="604800" />
	<security:logout invalidate-session="true" delete-cookies="remember-me, JSESSION_ID" 
		logout-url="/user/logout" logout-success-url="/" />
</security:http>