找不到CSRF令牌

时间:2015-08-28 00:08:24

标签: java xml spring jsp

我正在关注Spring安全性的教程,到目前为止我有以下内容: 当我尝试从登录页面登录时出现以下错误:

HTTP状态403 - 未找到预期的CSRF令牌。你的课程到期了吗?

我在stackoverflow上找到的解决方案表明要向表单添加隐藏属性,我就这样做了。这是属性:

<input type="hidden" name="${_csrf.parameterName}" value="{_csrf.token}"/>

我已多次重新检查代码并且我仍然遇到相同的403错误,即使我的代码似乎与Udemy教程完全匹配。

提前致谢。

我的login.jsp页面:

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

<html>

    <head>

        <title>Please login</title>
    </head>

    <body>

    <c:url value="/login" var="loginProcessingUrl"/>
 <form action="${loginProcessingUrl}" method="post">

    <fieldset>
        <legend>Please Login</legend>
        <!-- use param.error assuming FormLoginConfigurer#failureUrl contains the query parameter error -->
        <c:if test="${param.error != null}">
            <div>
                Failed to login.
                <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
                  Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
                </c:if>
            </div>
        </c:if>
        <!-- the configured LogoutConfigurer#logoutSuccessUrl is /login?logout and contains the query param logout -->
        <c:if test="${param.logout != null}">
            <div>
                You have been logged out.
            </div>
        </c:if>
        <p>
        <label for="username">Username</label>
        <input type="text" id="username" name="username"/>
        </p>
        <p>
        <label for="password">Password</label>
        <input type="password" id="password" name="password"/>
        </p>
        <!-- if using RememberMeConfigurer make sure remember-me matches RememberMeConfigurer#rememberMeParameter -->
        <p>
        <label for="remember-me">Remember Me?</label>
        <input type="checkbox" id="remember-me" name="remember-me"/>

        </p>


        <input type="hidden" name="${_csrf.parameterName}" value="{_csrf.token}"/>
        <div>
            <button type="submit" class="btn">Log in</button>
        </div>


    </fieldset>

 </form>

    </body>


</html>

我的index.jsp有一个注销表单:

    <!DOCTYPE html>

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

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

<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head> 
    <body>
        <c:url value="/showMessage.html" var="messageUrl" />
        <a href="${messageUrl}">Click to enter</a>

        <form action="logout" method="post">
            <input type="submit" value="logout"/>
            <input type="hidden" name="${_csrf.parameterName}" value="{_csrf.token}"/>

        </form>
    </body>
</html>

我的安全配置文件:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void congigureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }

    public void configure(HttpSecurity http) throws Exception{

        http.authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
        .loginPage("/login")
            .and()
        .httpBasic();
    }
}

空WebApplicationInitializer:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

登录控制器:

    @Controller
public class LoginController {

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public String loginPage(ModelMap map){

        //prefix: /WEB-INF/view
        //postfix .jsp
        //prefix + view + postfix
        // /WEB-INF/view/login.jsp
        return "login";

    }

这是我的application-config.xml

中的代码
<context:component-scan
        base-package="com.springsecurityexample"/>

这是我的mvc-config.xml文件中的代码:

<context:component-scan
        base-package="com.springsecurityexample.web"/> 


<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
</bean>

和我的web.xml文件:

<display-name>SpringSecurityTut1</display-name>

   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

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


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

2 个答案:

答案 0 :(得分:0)

也许你需要<form:form></form:form> 因为

 <input type="hidden"
               name="${_csrf.parameterName}"
               value="${_csrf.token}"/>

是spring'tag

答案 1 :(得分:0)

这是一个简单的错误,花了我一整天。我在登录页面和索引页面中忘记了我的值赋值中的“$”。

我有值=“{_ csrf.token} 而不是value =“$ {_ csrf.token}

就是这样。丢失美元符号!!感谢所有输入人员。