如何从cURL获取令牌?

时间:2017-03-13 23:24:01

标签: curl spring-security jwt

我正在使用Spring Security JWT,我想用cURL获取令牌:

@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> login(@RequestParam String username, @RequestParam String password,
        HttpServletResponse response) throws IOException {
    String token = null;
    AppUser appUser = appUserRepository.findOneByUsername(username);
    Map<String, Object> tokenMap = new HashMap<String, Object>();
    if (appUser != null && appUser.getPassword().equals(password)) {
        token = Jwts.builder().setSubject(username).claim("roles", appUser.getRoles()).setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
        tokenMap.put("token", token);
        tokenMap.put("user", appUser);
        return new ResponseEntity<Map<String, Object>>(tokenMap, HttpStatus.OK);
    } else {
        tokenMap.put("token", null);
        return new ResponseEntity<Map<String, Object>>(tokenMap, HttpStatus.UNAUTHORIZED);
    }
}

我试着用这个:

curl -X POST -H "Content-Type: application/json" localhost:8080/authenticate -d '{"username": "admin","password":"admin"}'

我收到此错误:

  

必需的字符串参数'username'

1 个答案:

答案 0 :(得分:1)

您的请求缺少usernamepassword参数,您应该使用参数data发送,而不是JSON:

curl -X POST http://localhost:8080/authenticate --data "username=admin&password=admin" 

如果您使用的是基本身份验证,则可以使用curl -u username:password xxx