【问题标题】:angularjs 400 bad request with REST service带有REST服务的angularjs 400错误请求
【发布时间】:2015-10-20 18:31:00
【问题描述】:

我在 Spring REST 应用程序中使用带有 Spring Security 的 AngularJs 进行身份验证和自动化。我向服务器发送登录请求, 这是我的角度服务:

angular.module('workflowService', ['ngResource']).
 factory('Utilisateur', function ($resource) {
  return $resource('rest/user/:action', {}, {
      authenticate: {
            method: 'POST',
            params: {'action' : 'authenticate'},
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 
                }
        },
  }
    );
 });

在服务器端,我有一个 Spring MVC 控制器,如下所述:

 @RequestMapping(value = "/user/authenticate", method = RequestMethod.POST, produces = "application/json")
  public  @ResponseBody TokenTransfer authenticate(@PathVariable  String username, @PathVariable String password)
{
    System.out.println( " appel authnticate ");
    System.out.println( "username  "+username+"  pass  "+password);

    UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(username, password);
    Authentication authentication = this.authManager.authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    /*
     * Reload user as password of authentication principal will be null after authorization and
     * password is needed for token generation
     */
    LdapUserDetails userDetails =(LdapUserDetails) this.userService.loadUserByUsername(username);

    return new TokenTransfer(TokenUtils.createToken(userDetails));
}

但我得到了:

POST http://localhost:8080/springrestprojet/rest/user/authenticate 400(错误请求)

【问题讨论】:

  • 可能你的身体数据不是应用程序/x-www-form-urlencoded。您是否尝试过应用程序/json?您可以查看 chrome 开发工具来检查正在发出的请求
  • 感谢@Paulo Santos 的建议。我尝试了 application/json ,但我仍然遇到同样的问题。

标签: angularjs spring rest security


【解决方案1】:

我找到了解决方案。问题出在 PathVariable 中,Path 中没有参数,只有 FormParam!我只是将我的代码更新为:

 @RequestMapping(value = "/user/authenticate", method = RequestMethod.POST, produces = "application/json")
   public  @ResponseBody TokenTransfer authenticate(@FormParam("username") String username, @FormParam("password") String password)
{
//no modification
}

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2013-06-22
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多