2016-01-22 44 views
2

我的应用程序有春季启动1.3.2,我试图使用春季安全与Spring MVC。春季安全阻止休息控制器

http://localhost:8080/admin下的管理面板和下http://localhost:8080/

我的网页内容为普通用户如果您正在试图打开管理面板(http://localhost:8080/admin)你必须登录,如果您是普通刚进入http://localhost:8080/和有乐趣无需登录。

我的安全配置类:

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("admin") 
       .password("password") 
       .roles("ADMIN"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/admin/**").hasRole("ADMIN") 
       .antMatchers("/**").permitAll() 
       .anyRequest().permitAll() 
       .and() 
       .formLogin() 
       .loginPage("/login"); 
    } 

} 

配置上面让我需要从/管理员 登录,但我有一些问题,对管理控制台功能。

这是控制器我试图从管理面板与POST请求:

@RestController 
@RequestMapping("/admin/v1") 
public class AdminController { 

    @RequestMapping(value = "/logout", method = RequestMethod.POST) 
    public String logout(HttpServletRequest request, HttpServletResponse response) { 
     String hello = "hi!"; 
     return hello; 
    } 
} 

所以我可以登录,浏览器渲染的管理控制台我,但是当我点击退出按钮,其信息发布注销方法从上面的Controller。应用告诉我403 Forbidden

有人可以告诉我我做错了什么吗?

+3

你能检查你的请求后包含CSRF令牌? – fateddy

回答

1

最有可能的403 Forbidden错误是因为默认情况下弹簧启用csrf保护。 您可以在配置中禁用csrf或在POST方法中包含CSRF令牌。

禁用CSRF在配置:

http 
    .csrf().disable() 
    .authorizeRequests() 
     .antMatchers("/admin/**").hasRole("ADMIN") 
     .antMatchers("/**").permitAll() 
     .anyRequest().permitAll() 
      .and() 
      .formLogin() 
      .loginPage("/login")      
     .and() 
     .logout() 
     .logoutSuccessUrl("/admin/v1/logout"); 

包含的CSRF令牌在表单提交:

<c:url var="logoutUrl" value="/admin/v1/logout"/> 
<form action="${logoutUrl}" method="post"> 
<input type="submit" value="Log out" /> 

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