spring security를 이용해 로그인 시스템 만들기 (1)

Spring Security

url마다 유저인증과 권한 설정을 할 수 있다.

맛보기

1) pom.xml에 org.springframework-version버전과 security 설정 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yakolla</groupId>
    <artifactId>blackjack</artifactId>
    <name>blackjack</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>4.0.2.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>     
        ...
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        ...

2) web.xml에 security-context.xml과 filter 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 
    <!-- 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>
    ...
    <!-- filter -->
    <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-app>

3) security-context.xml 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
            
    <http auto-config='true'>
        <intercept-url pattern="/**" access="ROLE_USER" />
    </http>
       
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="guest" password="guest" authorities="ROLE_USER"/>   
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

4) 웹서버 가동을 하면 다음과 같이 로그인 페이지가 자동으로 뜬다.

guest로 로그인을 하면 된다.


spring security는 커스터마이징을 할 수 있다.

다음에는 디비에 저장되어 있는 유저 계정과 로그인 페이지를 입맛에 맞게 변경해보자

넘어가기