auth与csrf令牌和cookie为我的休息客户端无法正常工作

时间:2018-04-15 16:33:38

标签: spring rest spring-mvc spring-boot resttemplate

背景

我有一个REST API,它使用resttemplate调用第三方rest API,需要csrf-token和用于auth的cookie,我在我的本地rest API中编写相同的csrf-token并试图点击控制器url但是它的失败... 我已经设置了从网络上获取的csrf-token和cookie用于auth,但是它给了我没有找到CSRF令牌。

public HttpHeaders buildHttpHeaders() {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("csrf_token", csrf_token);
    headers.set("Cookie", cookie);

    return headers;
}

邮递员回复

   {
    "data": {
        "ArchiveUser": null
    },
    "errors": [
        {
            "message": "No CSRF token was found!",
            "locations": [
                {
                    "line": 1,
                    "column": 39
                }
            ],
            "path": [
                "ArchiveUser"
            ]
        }
    ]
}

控制器

@RestController
@RequestMapping("/*")
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

   @RequestMapping(value="/create" ,method=RequestMethod.POST,consumes= {MediaType.APPLICATION_JSON_VALUE},produces= {MediaType.APPLICATION_JSON_VALUE})
   public ResponseEntity<?> createUser(@RequestBody CreateUserRequest createUserRequest){

       return userService.createUser(createUserRequest);
   }
}

UserService

@Value("${admin.csrf_token}")
private String csrf_token;

@Value("${admin.Cookie}")
private String cookie;

public ResponseEntity<?> createUser(CreateUserRequest createUserRequest) {
        createUserRequest.setQuery(createQueryString);
        Gson g = new Gson();
        logger.debug(g.toJson(createUserRequest));

        HttpEntity<CreateUserRequest> requestEntity = new HttpEntity<CreateUserRequest>(createUserRequest,
                buildHttpHeaders());
        logger.debug("httpenetity" + requestEntity);

        ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                String.class);
        return response;
    }

public HttpHeaders buildHttpHeaders() {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("csrf_token", csrf_token);
        headers.set("Cookie", cookie);

        return headers;
    }

yml输入

管理员:     csrf_token:xxxxx     Cookie:_csrf = xxxxxx

我被困在这里。

1 个答案:

答案 0 :(得分:0)

在我的代码重新上载后,这​​个问题得到解决,名称不匹配变量