2017-03-13 98 views
-1

我使用Spring Security的智威湯遜,我想與捲曲令牌:如何從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"}' 

,我得到這個錯誤:

Required String parameter 'username'

回答

1

您的請求缺少usernamepassword PARAMS,您應該將它們與參數data一起發送,而不是JSON:

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

如果您使用基本身份驗證,則可以使用curl -u username:password xxx

+0

當我使用這個curl -X POST http:// localhost:8080/authenticate --data「username = admin&password = admin」它返回{「token」:null} –