Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 基于spring安全令牌的身份验证_Java_Spring_Spring Security - Fatal编程技术网

Java 基于spring安全令牌的身份验证

Java 基于spring安全令牌的身份验证,java,spring,spring-security,Java,Spring,Spring Security,我尝试使用spring security实现基于令牌的身份验证,但我不知道如何正确实现它 有一个带有用户名、密码和recaptcha字段的登录表单。当我填写密码、用户名、recaptcha字段并单击submit时,我的凭证和recaptcha字段将被验证,如果可以,我需要生成令牌。 此令牌将存储在Windows本地存储中,将发送到服务器并在每次请求后进行验证 我在验证凭据后生成令牌时遇到一些困难 web.xml示例 <?xml version="1.0" encoding="UTF-8"?

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

有一个带有用户名、密码和recaptcha字段的登录表单。当我填写密码、用户名、recaptcha字段并单击submit时,我的凭证和recaptcha字段将被验证,如果可以,我需要生成令牌。 此令牌将存储在Windows本地存储中,将发送到服务器并在每次请求后进行验证

我在验证凭据后生成令牌时遇到一些困难

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>
<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>
captchavifierfilter.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;
    }
}
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;
    }

您的解决方案有缺陷,无法在并发环境中工作。您正在实例级别存储状态。请求2覆盖请求1中的值。你的意思是?实现我的问题的最佳方法是什么?不,你的筛选器有缺陷。你不需要在验证筛选器中执行所有操作之前执行筛选器,但是,您可能希望扩展默认的
UsernamePasswordAuthenticationFilter
,并通过验证所需的(重新)验证码来扩展它。您需要一个新的筛选器,它在登录筛选器之前执行(检查是否有有效的令牌),在登录筛选器之后执行以生成令牌。但是,你为什么要发明自己的产品呢?您可以使用SpringOAuth来完成这一切,它提供了令牌支持。