spring security 4.1 에서 사용자 정의 로그 인 인터페이스 와 확장 login controller

30858 단어 springsecurity
spring security 4.1.3 에서 로그 인 인터페이스 를 사용자 정의 하고 login contrller 의 실현 과 설정 방법 을 확장 합 니 다.
참고 문서: 사용자 정의 Login / Logout Filter, AuthenticationProvider, AuthenticationToken Spring Security Reference 1. 수요: 프로젝트 에서 spring security 로 권한 관 리 를 해 야 합 니 다.또한 login 의 기능 을 확장 해 야 합 니 다.예 를 들 어 로그 인 에 성공 한 후, 사용자 이름 을 session 에 넣 습 니 다. 2. 웹. xml 설정

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="Whale" version="3.1">
    <display-name>Whaledisplay-name>
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <async-supported>trueasync-supported>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>
            classpath:META-INF/applicationContext.xml,
            classpath:META-INF/applicationContext-security.xml
        param-value>
    context-param>
    
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:META-INF/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    <filter>
        <filter-name>springSecurityFilterChainfilter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChainfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <welcome-file-list>
        <welcome-file>/views/welcome.jspwelcome-file>
    welcome-file-list>
    <servlet-mapping>
        <servlet-name>jspservlet-name>
        <url-pattern>*.jspurl-pattern>
    servlet-mapping>
    <session-config>
        <session-timeout>10session-timeout>
    session-config>
web-app>

applicationContext-security.xml
<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-4.3.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd">
    <http auto-config="false">
        <intercept-url pattern="/" access="permitAll" />
        <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
        <intercept-url pattern="/dba**" access="hasRole('DBA')" />
        
        <form-login login-page="/views/login.jsp" username-parameter="username" password-parameter="password" authentication-failure-url="/views/accessDenied.jsp" />
        
        <custom-filter before="FORM_LOGIN_FILTER" ref="customLoginFilter" />
        
        <custom-filter before="LOGOUT_FILTER" ref="customLogoutFilter" />
    http>
    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service>
                <user name="user" password="user" authorities="ROLE_USER" />
                <user name="admin" password="root123" authorities="ROLE_ADMIN" />
                <user name="dba" password="dba" authorities="ROLE_ADMIN,ROLE_DBA" />
            user-service>
        authentication-provider>
    authentication-manager>
    
    <beans:bean id="customLoginFilter" class="com.ninelephas.whale.springsecurity.CustomLoginFilter">
        <beans:property name="authenticationManager" ref="authenticationManager" />
    beans:bean>
    
    <beans:bean id="customLogoutFilter" class="com.ninelephas.whale.springsecurity.CustomLogoutFilter">
        
        <beans:property name="filterProcessesUrl" value="/logout" />
        
        <beans:constructor-arg index="0" value="/" />
        <beans:constructor-arg index="1">
            
            <beans:array>
                <beans:bean id="securityContextLogoutHandler" class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
                
                <beans:bean id="customLogoutSuccessHandler" class="com.ninelephas.whale.springsecurity.CustomLogoutHandler" />
            beans:array>
        beans:constructor-arg>
    beans:bean>
beans:beans>
  • 몇 가 지 를 주의해 야 합 니 다. a. http auto - config = "false" 는 auto - config = "true" b 로 설정 할 수 없습니다. 사용자 정의 로그 인 인터페이스

    c. 사용자 정의 로그 인 filter

    d. authentication - manager 의 별명 을 정의 하고 filter 에 사용 하도록 지정 합 니 다

    e. 로그 인 filter 의 실현 클래스



  • 를 지정 합 니 다.
  • custom LoginFilter 의 코드 는 다음 과 같다.
  • /**
     * @Title: CustomLoginFilter.java
     * @Package com.ninelephas.whale.springsecurity
     * @Description: TODO
     *               Copyright: Copyright (c) 2016
     *               Company:      (  )    
     * 
     * @author roamerxv
     * @date 2016 9 6    11:23:31
     * @version V1.0.0
     */
    
    package com.ninelephas.whale.springsecurity;
    
    import java.io.IOException;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    
    /**
     * @ClassName: CustomLoginFilter
     * @Description: TODO
     * @author Comsys-roamerxv
     * @date 2016 9 6    11:23:31
     *
     */
    
    public class CustomLoginFilter extends UsernamePasswordAuthenticationFilter {
        /**
         * Logger for this class
         */
        private static final Logger logger = LogManager.getLogger(CustomLoginFilter.class.getName());
    
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            logger.debug("attemptAuthentication(HttpServletRequest, HttpServletResponse) - start"); //$NON-NLS-1$
    
            String username = obtainUsername(request).toUpperCase().trim();
            String password = obtainPassword(request);
            Authentication returnAuthentication = null;
            try {
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                returnAuthentication = this.getAuthenticationManager().authenticate(authRequest);
            } catch (Exception e) {
                logger.error(e);
                throw e ;
            }
    
            logger.debug("attemptAuthentication(HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
            return returnAuthentication;
        }
    
        @Override
        protected void successfulAuthentication(HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
            logger.debug("successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication) - start"); //$NON-NLS-1$
            super.successfulAuthentication(request, response, chain, authResult);
            logger.debug("    !");
            logger.debug("successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication) - end"); //$NON-NLS-1$
        }
    
        @Override
        protected void unsuccessfulAuthentication(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
            logger.debug("unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) - start"); //$NON-NLS-1$
            super.unsuccessfulAuthentication(request, response, failed);
            logger.debug("    !");
            logger.debug("unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) - end"); //$NON-NLS-1$
        }
    }
    

    CustomLogoutFilter.java
    /**
     * @Title: CustomLogoutFilter.java
     * @Package com.ninelephas.whale.springsecurity
     * @Description: TODO
     *               Copyright: Copyright (c) 2016
     *               Company:      (  )    
     * 
     * @author roamerxv
     * @date 2016 9 6    3:13:07
     * @version V1.0.0
     */
    
    package com.ninelephas.whale.springsecurity;
    
    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.LogManager;
    
    import org.springframework.security.web.authentication.logout.LogoutFilter;
    import org.springframework.security.web.authentication.logout.LogoutHandler;
    import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
    
    /**
     * @ClassName: CustomLogoutFilter
     * @Description: TODO
     * @author Comsys-roamerxv
     * @date 2016 9 6    3:13:07
     *
     */
    
    public class CustomLogoutFilter extends LogoutFilter {
        /**
         * Logger for this class
         */
        private static final Logger logger = LogManager.getLogger(CustomLogoutFilter.class.getName());
    
        /**
         * 
         *          CustomLogoutFilter.
         * 

    * Title: *

    *

    * Description: *

    * * @param logoutSuccessHandler * @param handlers */
    public CustomLogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers) { super(logoutSuccessUrl, handlers); logger.debug("CustomLogoutFilter(String, LogoutHandler[]) - start"); //$NON-NLS-1$ logger.debug("CustomLogoutFilter(String, LogoutHandler[]) - end"); //$NON-NLS-1$ } public CustomLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) { super(logoutSuccessHandler, handlers); logger.debug("CustomLogoutFilter(LogoutSuccessHandler, LogoutHandler[]) - start"); //$NON-NLS-1$ logger.debug("CustomLogoutFilter(LogoutSuccessHandler, LogoutHandler[]) - end"); //$NON-NLS-1$ } }

    CustomLogoutHandler.java
    /**
     * @Title: CustomLogoutHandler.java
     * @Package com.ninelephas.whale.springsecurity
     * @Description: TODO
     * Copyright: Copyright (c) 2016
     * Company:      (  )    
     * 
     * @author roamerxv
     * @date 2016 9 6    3:38:30
     * @version V1.0.0
     */
    
    package com.ninelephas.whale.springsecurity;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.web.authentication.logout.LogoutHandler;
    
    /**
      * @ClassName: CustomLogoutHandler
      * @Description: TODO
      * @author Comsys-roamerxv
      * @date 2016 9 6    3:38:30
      *
      */
    
    public class CustomLogoutHandler implements LogoutHandler {
        /**
         * Logger for this class
         */
        private static final Logger logger = LogManager.getLogger(CustomLogoutHandler.class.getName());
    
        /**
    
          *          CustomLogoutHandler. 
          * 

    Title:

    *

    Description:

    * @param logoutSuccessHandler * @param handlers */
    public CustomLogoutHandler() { } public void logout(HttpServletRequest request,HttpServletResponse response, Authentication authentication){ logger.debug("logout(HttpServletRequest, HttpServletResponse, Authentication) - start"); //$NON-NLS-1$ logger.debug("logout(HttpServletRequest, HttpServletResponse, Authentication) - end"); //$NON-NLS-1$ } }

    좋은 웹페이지 즐겨찾기