Spring security 기본적인 설정과 예제
제일 먼저,
pom.xml 디펜던시
https://mvnrepository.com/search?q=security 로 들어간 다음
검색어에 security를 검색하면 쭈욱 라이브러리들이 나온다.
버전은 알아서 맞게 찾아서 추가해주면 된다.
실행 캡쳐들
시큐리티 필터로 인해서 로그인 하기전에는 /login으로 인터셉터가 가로챈다.
login 폼은 무료 부트스트랩을 폼을 이용했다.

security-context.xml에서 설정 해놓은 guest / guest 로 로그인하지 않으면
/denied 로 매핑되어있다.

guest / guest로 로그인 했을경우 /home url로 매핑이 된다.

/home 에서 로그아웃 버튼을 눌렀을 경우 로그아웃이 정상적으로 동작한다.

전체 프로젝트 코드는 아래 github 주소에 있습니다.
https://github.com/ndgndg91/springJPA_and_Security_Study
pom.xml 디펜던시
https://mvnrepository.com/search?q=security 로 들어간 다음
검색어에 security를 검색하면 쭈욱 라이브러리들이 나온다.
버전은 알아서 맞게 찾아서 추가해주면 된다.
Spring Security Web, Spring Security Config
기본적으로 두가지가 최소 요건이라고 한다.
하지만 필자는 정확히는 잘 모르지만
Spring Security Core
까지 추가했다.
시간을 더 할애해서 파고 들어서 공부해봐야 할 것 같다.
필자는 properties 설정에서
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
버전을 잡아줬기 때문에 아래와 같이 버전을 잡았다.
물론 ${org.springframework-version} 이렇게 해도 되지만, 확실히 보기 위해서..
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
다음은 web.xml에 빨간색을 추가해준다.
<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>
그리고 아래 필터를 등록해준다.
<!-- spring security -->
<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>
web.xml에서 추가해준 security-context.xml 이다.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd ">
<http auto-config='true' use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/denied" access="permitAll" />
<intercept-url pattern="/resources/**"
access="permitAll" />
<intercept-url pattern="/**"
access="hasRole('ROLE_USER')" />
<form-login login-page="/login" default-target-url="/home"
username-parameter="username" password-parameter="password"
authentication-failure-url="/denied" always-use-default-target='true' />
<logout invalidate-session="true"
logout-url="/j_spring_security_logout" logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="guest" password="guest" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
그리고 HomeController
package com.spring.ndgndg91;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
@RequestMapping(value="/login", method= RequestMethod.GET)
public ModelAndView loginProcess(ModelAndView mv) {
mv.setViewName("login");
return mv;
}
@RequestMapping("/denied")
public String denied() {
return "denied";
}
@RequestMapping("/logout")
public String logout() {
return "logout";
}
}
실행 캡쳐들
시큐리티 필터로 인해서 로그인 하기전에는 /login으로 인터셉터가 가로챈다.
login 폼은 무료 부트스트랩을 폼을 이용했다.

security-context.xml에서 설정 해놓은 guest / guest 로 로그인하지 않으면
/denied 로 매핑되어있다.

guest / guest로 로그인 했을경우 /home url로 매핑이 된다.

/home 에서 로그아웃 버튼을 눌렀을 경우 로그아웃이 정상적으로 동작한다.

전체 프로젝트 코드는 아래 github 주소에 있습니다.
https://github.com/ndgndg91/springJPA_and_Security_Study
댓글
댓글 쓰기