스프링

스프링 시큐리티(Spring Security)

  • 스프링 시큐리티를 사용하여 로그인 인증을 하는 간단한 예제
  • 스프링 시큐리티는 서블릿의 root context를 사용하므로 반드시 web.xml에 컨텍스트가 기술된 xml이 존재해야한다.
  • 스프링 시큐리티의 3.2.3.RELEASE기준이나 4.0.4에서도 작동을 확인하였음

pom.xml

스프링 시큐리티 디펜던시

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<properties>

    <java-version>1.6</java-version>

    <org.springframework-version>3.2.8.RELEASE</org.springframework-version>

    <org.springframework-security-version>3.2.3.RELEASE</org.springframework-security-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>${org.springframework-security-version}</version>

    </dependency>

    <dependency>

        <groupId>org.springframework.security</groupId>

        <artifactId>spring-security-config</artifactId>

        <version>${org.springframework-security-version}</version>

    </dependency>

web.xml

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

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 

    <!-- 서블릿 파라미터 -->

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

     

    <!-- Creates the Spring Container shared by all Servlets and Filters -->

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

     

    <!-- 스프링 세션  리스너 등록 -->

    <listener>

        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>

    </listener>

     

    <!-- 스프링 보안 필터 -->

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

     

    <!-- Processes application requests -->

    <servlet>

        <servlet-name>appServlet</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>

        </init-param>

        <load-on-startup>1</load-on-startup>

    </servlet>

         

    <servlet-mapping>

        <servlet-name>appServlet</servlet-name>

        <url-pattern>/</url-pattern>

    </servlet-mapping>

 

</web-app>

security-context.xml

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

30

31

32

33

34

35

36

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

    xmlns:jee="http://www.springframework.org/schema/jee"

    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd

        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd

        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

         

    <http auto-config='true' >

        <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/login_duplicate" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/**" access="ROLE_USER" />

        <form-login login-page="/login"

                    username-parameter="id"

                    password-parameter="pw"    

                    login-processing-url="/loginProcess"

                    default-target-url="/login_success"

                    authentication-failure-url="/login"

                    always-use-default-target='true'

                    />

         

        <session-management>

            <concurrency-control max-sessions="1" expired-url="/login_duplicate"/>

        </session-management>

    </http>

     

    <beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

     

    <authentication-manager>

        <authentication-provider ref="customAuthenticationProvider"/>

    </authentication-manager>

     

    <beans:bean id="customAuthenticationProvider" class="com.security.sample.CustomAuthenticationProvider"/>

     

</beans:beans>

LoginController.java

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

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

package com.security.sample;

 

 

import javax.servlet.http.HttpSession;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

@Controller

public class LoginController {

     

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

     

    /**

     * Simply selects the home view to render by returning its name.

     */

    @RequestMapping(value = "login", method = RequestMethod.GET)

    public void login(HttpSession session) {

        logger.info("Welcome login! {}", session.getId());

    }

     

    @RequestMapping(value = "logout", method = RequestMethod.GET)

    public void logout(HttpSession session) {

        CustomUserDetails userDetails = (CustomUserDetails)session.getAttribute("userLoginInfo");

         

        logger.info("Welcome logout! {}, {}", session.getId(), userDetails.getUsername());

         

         

        session.invalidate();

    }

     

    @RequestMapping(value = "login_success", method = RequestMethod.GET)

    public void login_success(HttpSession session) {

        CustomUserDetails userDetails = (CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getDetails();

         

        logger.info("Welcome login_success! {}, {}", session.getId(), userDetails.getUsername() + "/" + userDetails.getPassword());

        session.setAttribute("userLoginInfo", userDetails);

    }

     

    @RequestMapping(value = "page1", method = RequestMethod.GET)

    public void page1() {      

    }

     

    @RequestMapping(value = "login_duplicate", method = RequestMethod.GET)

    public void login_duplicate() {    

        logger.info("Welcome login_duplicate!");

    }

     

}

CustomUserDetails.java

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

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

package com.security.sample;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

 

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

 

public class CustomUserDetails implements UserDetails {

 

    private static final long serialVersionUID = -4450269958885980297L;

    private String username;

    private String password;

     

    public CustomUserDetails(String userName, String password)

    {

        this.username = userName;

        this.password = password;

    }

     

    @Override

    public Collection<? extends GrantedAuthority> getAuthorities() {

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();   

        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

         

        return authorities;

    }

  

    @Override

    public String getPassword() {

        return password;

    }

  

    @Override

    public String getUsername() {

        return username;

    }

  

    @Override

    public boolean isAccountNonExpired() {

        return true;

    }

  

    @Override

    public boolean isAccountNonLocked() {

        return true;

    }

  

    @Override

    public boolean isCredentialsNonExpired() {

        return true;

    }

  

    @Override

    public boolean isEnabled() {

        return true;

    }

 }

CustomAuthenticationProvider.java

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

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

package com.security.sample;

 

import java.util.ArrayList;

import java.util.List;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.security.authentication.AuthenticationProvider;

import org.springframework.security.authentication.BadCredentialsException;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

 

public class CustomAuthenticationProvider implements AuthenticationProvider { 

      

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

     

    @Override

    public boolean supports(Class<?> authentication) {

        return authentication.equals(UsernamePasswordAuthenticationToken.class);

    }

  

    @Override

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

         

        String user_id = (String)authentication.getPrincipal();    

        String user_pw = (String)authentication.getCredentials();

         

         

        logger.info("사용자가 입력한 로그인정보입니다. {}", user_id + "/" + user_pw);

         

        if(user_id.equals("test")&&user_pw.equals("test")){

            logger.info("정상 로그인입니다.");

            List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();

            roles.add(new SimpleGrantedAuthority("ROLE_USER"));

             

            UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user_id, user_pw, roles);

            result.setDetails(new CustomUserDetails(user_id, user_pw));

            return result;         

        }else{

            logger.info("사용자 크리덴셜 정보가 틀립니다. 에러가 발생합니다.");

            throw new BadCredentialsException("Bad credentials");

        }

    }

}

login.jsp

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page session="false" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<html>

<head>

    <title>로그인페이지</title>  

</head>

  

<body>

<h2>로그인 </h2>

<form name="form" method="post" action="loginProcess">

<table>

    <tr height="40px">

        <td>사용자아이디</td>

        <td><input type="text" name="id"></td>

    </tr>

    <tr height="40px">

        <td>패스워드</td>

        <td><input type="password" name="pw"></td>

    </tr>

</table>

<table>

    <tr>

        <td align="center"><input type="submit" value="로그인"></td>

        <td align="center"><input type="reset" value="리셋"></td>

    </tr>

</table>

</form>

</body>

</html>

 

about author

PHRASE

Level 60  머나먼나라

Accidents will happen. (사고란 일어나기 마련이다)

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more