2013-10-19 76 views
10

我试图确保我的网站使用Spring安全性遵循网络上的指南。所以,在我的服务器端WebSecurityConfigurerAdapter和控制器看起来像这样弹簧安全403错误

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
implements ApplicationContextAware { 

@Override 
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception { 
authManagerBuilder.inMemoryAuthentication() 
.withUser("user").password("password").roles("ADMI N"); 
} 
} 

@Controller 
//@RequestMapping("/course") 
public class CourseController implements ApplicationContextAware{ 

@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json") 
public @ResponseBody List<Course> get(// The critirion used to find. 
@RequestParam(value="what", required=true) String what, 
@RequestParam(value="value", required=true) String value) { 
//..... 
} 

@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json") 
public List<Course> upload(@RequestBody Course[] cs) { 
} 
} 

什么困惑我很是服务器不向POST/DELETE方法作出回应,而GET方法工作正常。顺便说一句,我在客户端使用RestTemplate。例外是:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 403 Forbidden 
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:574) 
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:530) 
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:487) 
    at org.springframework.web.client.RestTemplate.delete(RestTemplate.java:385) 
    at hello.Application.createRestTemplate(Application.java:149) 
    at hello.Application.main(Application.java:99) 

我在互联网上搜索了几天。仍然没有线索。请帮忙。非常感谢

+0

是正确的?角色(“ADMI N”)。 'I'和'N'之间有一个空格。 –

回答

29

该问题很可能是由于。如果用户不会在Web浏览器中使用您的应用程序,则可以使用then it is safe to disable CSRF保护。否则,你应该确保include the CSRF token in the request

disable CSRF protection您可以使用以下方法:

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig 
    extends WebSecurityConfigurerAdapter implements ApplicationContextAware { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      // ... 
      .csrf().disable(); 
    } 

    @Override 
    protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception { 
     authManagerBuilder 
      .inMemoryAuthentication() 
       .withUser("user").password("password").roles("ADMIN"); 
    } 
} 
+0

感谢罗布。这是csrf问题。是的,我不希望我的用户使用网络浏览器来使用我的应用程序。 它在客户端运行良好。但在服务器端我得到这个: o.s.web.servlet.PageNotFound:请求方法'POST'不支持 奇怪。 我应该忽略它吗? – ken

+1

我认为PageNotFound是一个单独的问题,我会解决。可能您需要发布另一个问题,并提供更多关于此错误的信息。 –