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

Wonjun Seo·2023년 6월 1일
0

JSP에서 Spring Security 사용하기

pom.xml 설정

pom.xml에 아래 dependency를 추가한다.

<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>

References

https://lifere.tistory.com/entry/Spring-%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0%EB%A5%BC-JSP%EC%97%90%EC%84%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

0개의 댓글