基于Spring安全令牌的身份验证

时间:2014-12-29 15:45:06

标签: java spring spring-security

我尝试使用spring security实现基于令牌的身份验证,但我不知道如何正确实现它!

有一个包含用户名,密码和recaptcha字段的登录表单。当我填写密码,用户名,重新访问字段并单击提交时,我的凭据和记录字段将被验证,如果可以,我需要生成令牌。 此令牌将存储在窗口本地存储中,将在每次请求后发送到服务器并进行验证!

验证凭证后,我在令牌生成方面遇到了一些困难!

web.xml示例

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


  <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml,
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>


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



    <!--Spring security filter configuration-->
    <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>



    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>
            org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
        </filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

spring-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-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

<!--     enable use-expressions-->
    <http  auto-config="true" >
        <session-management invalid-session-url="/login" />
        <access-denied-handler error-page="/403.jsp" />
        <intercept-url pattern="/dashboard**" access="ROLE_ADMIN" />
        <intercept-url pattern="/dashboard/**" access="ROLE_ADMIN" />
        <intercept-url pattern="/login" access="permitAll" />
        <form-login
                login-page="/login"
                authentication-failure-url="/login?error=true"
                username-parameter="username"
                password-parameter="password"
                default-target-url="/dashboard"
                />

        <session-management>
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>
        <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <logout
                invalidate-session="true"
                logout-success-url="/login"
                logout-url="/logout"
        />
        <csrf/>
        <custom-filter ref="beforeCaptureFilter" before="FORM_LOGIN_FILTER"/>
        <custom-filter ref="captchaVerifierFilter" after="FORM_LOGIN_FILTER"/>
    </http>




    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="SELECT U.username, U.password,
                                           CASE U.enabled
                                                WHEN 1 THEN 'true'
                                                    ELSE 'false'
                                            END 'enabled'
                                           FROM users U WHERE BINARY U.username=?"
               authorities-by-username-query="SELECT U.username,  R.role FROM users U
                                                JOIN roles R ON R.id = U.role_id
                                                WHERE BINARY U.username=?"/>
            <password-encoder ref="encoder" />
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="captchaVerifierFilter" class="com.test.auth.CaptchaVerifierFilter">
        <beans:property name="useProxy" value="false"/>
        <beans:property name="proxyPort" value=""/>
        <beans:property name="proxyHost" value=""/>
        <beans:property name="failureUrl" value="/login?error=true"/>
        <beans:property name="captchaFilter" ref="beforeCaptureFilter"/>
        <beans:property name="privateKey" value="recaptcha key"/>
    </beans:bean>

    <beans:bean id="beforeCaptureFilter" class="com.test.auth.BeforeCapthaFilter" />
    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="10" />
    </beans:bean>

</beans:beans>

beforeCaptchaFilter.java示例

public class BeforeCapthaFilter extends OncePerRequestFilter {
    protected static  Logger logger = Logger.getLogger("filter");
    private String recaptchaResponse = null;
    private String recaptchaChallenge = null;
    private String remoteAddress = null;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getParameter("recaptcha_response_field") != null) {
            recaptchaResponse = httpServletRequest.getParameter("recaptcha_response_field");
            recaptchaChallenge = httpServletRequest.getParameter("recaptcha_challenge_field");
            remoteAddress = httpServletRequest.getRemoteAddr();
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    public String getRecaptchaResponse() {
        return recaptchaResponse;
    }

    public void setRecaptchaResponse(String recaptchaResponse) {
        this.recaptchaResponse = recaptchaResponse;
    }

    public String getRecaptchaChallenge() {
        return recaptchaChallenge;
    }

    public void setRecaptchaChallenge(String recaptchaChallenge) {
        this.recaptchaChallenge = recaptchaChallenge;
    }

    public String getRemoteAddress() {
        return remoteAddress;
    }

    public void setRemoteAddress(String remoteAddress) {
        this.remoteAddress = remoteAddress;
    }
}

CaptchaVerifierFilter.java示例

public class CaptchaVerifierFilter extends OncePerRequestFilter {
    protected static Logger logger = Logger.getLogger("filter");
    private boolean useProxy = false;
    private String proxyPort;
    private String proxyHost;
    private String failureUrl;
    private BeforeCapthaFilter captchaFilter;
    private String privateKey;
    // Inspired by log output: AbstractAuthenticationProcessingFilter.java:unsuccessfulAuthentication:320)
    // Delegating to authentication failure handlerorg.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@15d4273
    private SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (captchaFilter.getRecaptchaResponse() != null) {
            // Create a new recaptcha (by Soren Davidsen)
            ReCaptchaImpl reCaptcha = new ReCaptchaImpl();

            // Set the private key (assigned by Google)
            reCaptcha.setPrivateKey(privateKey);

            // Assign proxy if needed
            if (useProxy) {
                Properties systemSettings = System.getProperties();
                systemSettings.put("http.proxyPort",proxyPort);
                systemSettings.put("http.proxyHost",proxyHost);
            }

            // Send HTTP request to validate user's Captcha
            ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(captchaFilter.getRemoteAddress(),
                    captchaFilter.getRecaptchaChallenge(), captchaFilter.getRecaptchaResponse());
            // Check if valid
            if (!reCaptchaResponse.isValid()) {
                SecurityContextHolder.getContext().setAuthentication(null);
            }

            // Reset Captcha fields after processing
            // If this method is skipped, everytime we access a page
            // CaptchaVerifierFilter will infinitely send a request to the Google Captcha service!
            resetCaptchaFields();
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        // Proceed with the remaining filters
    }

    public boolean isUseProxy() {
        return useProxy;
    }

    public void setUseProxy(boolean useProxy) {
        this.useProxy = useProxy;
    }

    public void resetCaptchaFields() {
        captchaFilter.setRecaptchaChallenge(null);
        captchaFilter.setRecaptchaResponse(null);
        captchaFilter.setRemoteAddress(null);
    }

    public String getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(String proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public String getFailureUrl() {
        return failureUrl;
    }

    public void setFailureUrl(String failureUrl) {
        this.failureUrl = failureUrl;
    }

    public BeforeCapthaFilter getCaptchaFilter() {
        return captchaFilter;
    }

    public void setCaptchaFilter(BeforeCapthaFilter captchaFilter) {
        this.captchaFilter = captchaFilter;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

0 个答案:

没有答案