2016-09-16 10 views
0

Приношу свои извинения за беспорядочный синтаксис HTML ниже. Когда у меня включен csrf http.authorizeRequest(), я продолжаю получать ошибку 403. Конечно, если у меня есть csrf.disable(), все будет хорошо.Почему Spring csrf дает мне ошибку сети 403?

Полагаю, что тег <form:form> автоматически использовал токен CSRF, что должно быть так, потому что URL-адрес ниже перестает работать.

Может кто-нибудь сказать мне, что это такое, чего я не понимаю?

NetworkError: 403 Forbidden - http://localhost:8080/AssetCore/createGuideline/

Мой класс конфигурации:

@SuppressWarnings("deprecation") 
@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter{ 
    private final Logger log = Logger.getLogger (this.getClass()); 
    /** 
    * This class gets called during startup. 
    */ 

    /** 
    * Configure http security. 
    */ 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     /** 
     * This method gets called when the app starts up. 
     * I believe that all the patterns for the MVC and rest calls will need to go here. 
     */ 
     log.info("configure(): called to set up authorizedRequest pattern matching."); 
     http 
      .logout().logoutSuccessUrl("/login?loggedout=true").invalidateHttpSession(true).deleteCookies("JSESSIONID") 
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); 
     http.authorizeRequests() 
      .antMatchers(HttpMethod.PUT, "/assessment/**").permitAll() 
      .antMatchers("/createGuideline/**",).permitAll()  
    } 

СПЯ:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> 
<%@ taglib prefix="ark" tagdir="/WEB-INF/tags" %> 
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta http-equiv="content-type" 
      content="text/html; charset=windows-1252"> 
     <meta charset="utf-8"> 
     <title>ASSET Core - PCC</title> 
     <jsp:include page="ourCSSandJS.jsp" /> 
     <link rel="stylesheet" href="/AssetCore/resources/css/pccStyle.css"> 
     <link rel="stylesheet" href="/AssetCore/resources/css/scrollbar.css"> 
     <link rel="stylesheet" href="/AssetCore/resources/css/mcp_style.css"> 
     <script>var storedFormatExtraArgs = [];</script> 
     <script src="/AssetCore/resources/js/valid/pcc.js"></script> 
     <script src="/AssetCore/resources/js/controlFormatting.js"></script> 
     <script src="/AssetCore/resources/js/valid/controlCard.js"></script> 
     <script src="/AssetCore/resources/js/thirdParty/jquery.scrollbar.min.js"></script> 
     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
    </head> 
    <body>`      <form:form id="customGuide" method="POST" 
          action="/AssetCore/createGuideline"> 
          <fieldset> 
           <legend id="createGuideline">Create Guideline</legend> 
           <p> 
            <label for="gName">Name</label><br /> <input type="text" 
             id="gName" name="gName" /> 
           </p>` 
+0

На первый взгляд, он должен работать. Попробуйте в Chrome и посмотрите в сетевом инспекторе, чтобы узнать, находится ли токен csrf в сообщении формы. – Taylor

+0

Я не думаю, что это так. Это то, что я получил: Запрос URL: HTTP: // локальный: 8080/AssetCore/createGuideline/ Запрос Метод: POST Код состояния: 403 Forbidden Удаленный адрес: [:: 1]: 8080 Response Headers просмотреть исходный Cache-Control: no-cache, no-store, max-age = 0, must-revalidate Content-Language: en-US Content-Length: 2106 Content-Type: text/html; charset = ISO-8859- 1 Дата: Пт, 16 сентября 2016 19:14:44 GMT Expires: 0 Pragma: нет кэша Сервер: Apache-Coyote/1.1 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode = block Заголовок запроса – DenisMP

+1

Это заголовки ответов (я думаю), если только я неправильно читаю документы, они будут в теле запроса. – Taylor

ответ

0

Итак, документация Spring не является правильным, по крайней мере, не то, что я видел. Я на самом деле добавил следующее к <form:form> теге

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

И теперь он работает.

Смежные вопросы