본문 바로가기

스프링

스프링 시큐리티(spring security) 설정

반응형

먼저 프로젝트를 생성하고, 스프링의 버전을 조정합니다.

pom.xml 파일을 이용해서 수정하면 별도의 과정 없이 처리 가능합니다. 

스프링 시큐리티는 스프링의 여러 하위 프로젝트 중에 하나이므로 필요한 버전을 추가합니다.

그리고 스프링 시큐리티 관련 태그 라이브러리를 활용할 수 있도록 spring-security-taglib도 추가합니다.

pom.xml의 일부


<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-web</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
		
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-config</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
		
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-core</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
		
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>

 

security-context.xml 생성

그 다음은 security-context.xml을 생성합니다.                                                                                           

스프링 시큐리티는 단독으로 설정이 가능하여 기존의 root-context.xml과는 별도로 따로 작성하는 것이 좋습니다.  security-context.xml 파일은 메뉴에서 'Spring Bean Configuration File'을 통해 생성하거나 일반 xml 파일로 생성할 수 있습니다. 

작성한 security-context.xml은 Namespaces에서 security 항목을 체크합니다.

xml 을 이용해서 스프링 시큐리티를 설정할 때에는 5.0 네임스페이스에서 문제가 발생하기 때문에 security-context.xml을 수정합니다. (4.2 버전까지는 허용이 되지만 5.0은 에러가 발생하는 버그가 있다.)

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security.xsd
	http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">

 

web.xml 설정

스프링 시큐리티가 스프링 MVC에서 사용되기 위해서는 필터를 이용해서 스프링 동작에 관여하도록 설정합니다.

web.xml의 일부

<filter>
	<filter-name>springSecurityFilterChain</filter-name>
	<filter-class>org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>
<filter-mapping>
	<filter-name>springSecurityFilterChain</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

이렇게만 하면 springSecurityFilterChain이라는 빈이 제대로 설정되지 않아서 에러가 납니다.                                   

스프링 시큐리티의 설정파일을 찾을 수 있게 처리를 해줍니다.

web.xml의 일부

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml
		/WEB-INF/spring/security-context.xml</param-value>
	</context-param>
security-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security.xsd
	http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">

	<security:http>
    	
        <security:form-login />
        
	</security:http>
	
	<security:authentication-manager>
		
	</security:authentication-manager>
	
</beans>

 

시큐리티가 필요한 URI 설계

 스프링 시큐리티의 최소한의 설정이 완료되었습니다. 이제 시큐리티에 의해 제어가 필요한 URI를 설계하고 적용하도록 합니다.

  • /sample/all -> 로그인을 하지 않은 사용자도 접근 가능한 URI
  • /sample/member -> 로그인 한 사용자들만이 접근할 수 있는 URI
  • /sample/admin -> 로그인 한 사용자들 중에서 관리자 권한을 가진 사용자만 접근할 수 있는 URI

com.security.controller 패키지 내에 SampleController를 작성하고 해당 URI에 맞는 메서드를 작성합니다.

SampleController 클래스

package com.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.log4j.Log4j;

@Log4j
@RequestMapping("/sample/*")
@Controller
public class SampleController {
	
	@GetMapping("/all")
	public void doAll() {
		log.info("do all can access everybody");
	}
	
	@GetMapping("/member")
	public void doMember() {
		log.info("logined member");
	}
	
	@GetMapping("/admin")
	public void doAdmin() {
		log.info("admin only");
	}
	
}

views 폴더에 해당 URI에 맞는 화면을 작성합니다.

이제 프로젝트를 실행하고 해당 URI가 정상작동하는지 확인합니다(기본 경로는 "/"로 세팅)

all.jsp의 일부

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http//
www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>/sample/all page</h1>
</body>
</html>

나머지도 동일하게 하고 <h1>태그의 내용만 구분 가능하게 작성합니다.

 

반응형