2017-05-24 88 views
1

我在SpringMVC中使用Spring Security進行應用程序。在春季安全xml配置文件我啓用csrf使用<csrf/>。在html中查看工作正常時,我添加csrf令牌鏈接形式,但現在我想添加控制器,並作了一些休息通信。控制器看起來是這樣的:SpringMVC與其餘控制器 - 不支持請求方法'POST'

@Controller 
public class RestControllerTest { 
    @RequestMapping(value = "/rest", method = RequestMethod.POST, produces = "application/json") 
    @ResponseStatus(value = HttpStatus.OK) 
    public @ResponseBody void setUser(@RequestBody User user){ 
     System.out.println("Witaj " + user.getFirstname() + "!"); 
    } 
} 

當我嘗試與用戶(使用郵遞員)發送JSON:

{ 
    "firstname": "name", 
    "lastname": "name" 
} 

我收到404個Not Found狀態的郵遞員和STS WARN : org.springframework.web.servlet.PageNotFound - Request method 'POST' not supported。我知道我必須使用csrf標記,但我不知道如何做到這一點。 enter image description here

+1

您的應用程序是否成功部署?什麼是你試圖發佈這些數據的完整URL? –

+0

是的,應用程序正常工作。所有返回視圖的控制器都很好。當我禁用csrf我可以發送json用戶使用郵遞員,但是當我啓用csrf我不幸有問題女巫發佈方法。 – lukhol

+1

對於csrf令牌:https://stackoverflow.com/questions/27182701/how-do-i-send-spring-csrf-token-from-postman-rest-client 雖然你描述的問題似乎並不是由它引起的,因爲缺乏令牌會給你一個403. 是你的整個控制器?你在課堂上有前綴請求映射嗎? 編輯 - 只看到你的迴應。那麼,如果你在postman作品中禁用csrf相同的請求? – chaos

回答

1

我有一個類似於你的工作用例。這就是我的情況。

我Filter類 -

public class MyCsrfFilter extends OncePerRequestFilter { 

    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
     FilterChain filterChain) 
      throws Exception { 
     CsrfToken csrf = (CsrfToken) request.getAttribute(org.springframework.security.web.csrf.CsrfToken.class.getName()); 
     if (csrf != null) { 
      Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); 
      String token = csrf.getToken(); 
      if (cookie == null) { 
       cookie = new Cookie("XSRF-TOKEN", token); 
       cookie.setPath(YOUR_DOMAIN_NAME); 
       cookie.setHttpOnly(true); 
       response.addCookie(cookie); 
      } 
     } 
     filterChain.doFilter(request, response); 
    } 

} 

下面是彈簧啓動的安全配置。如果您需要,可以將其轉換爲等效的xml配置文件。

@Configuration 
@EnableWebMvcSecurity 
public class CustomWebSecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf() 
       .csrfTokenRepository(getTokenRepo()) 
       .and() 
       .authorizeRequests() 
       .antMatchers("/login", "/login**").permitAll() 
       .and() 
       .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class); 
    } 

    private CsrfTokenRepository getTokenRepo() { 
     HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository(); 
     repo.setHeaderName("X-XSRF-TOKEN"); 
     return repo; 
     } 

希望這有助於!

相關問題