我必须向我的restful服务发出HTTP.Post(Android App),以注册新用户!
问题是,当我尝试向注册终端发出请求(没有安全性)时,Spring一直阻止我!
我的项目依赖关系
MysqL.connector.version>5.1.30MysqL.connector.version>
春季安全
调节器
@RestController
@RequestMapping(value="/webapi/cadastro",produces="application/json")
public class CadastroController {
@Autowired
UsuarioService usuarioService;
Usuario u = new Usuario();
@RequestMapping(value="/novo",method=RequestMethod.POST)
public String register() {
// this.usuarioService.insert(usuario);
// usuario.setPassword(HashMD5.criptar(usuario.getPassword()));
return "teste";
}
}
JS Post(Angular)
$http.post('/webapi/cadastro/novo').success(function(data) {
alert('ok');
}).error(function(data) {
alert(data);
});
而错误
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
—解决方案—
实现了一个过滤器,将我的X-XSRF-TOKEN连接到每个请求标头
public class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain)
throws ServletException,IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request,"XSRF-TOKEN");
String token = csrf.getToken();
if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN",token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request,response);
}
}
添加到此过滤器的映射到web.xml并完成!