Spring:使用授权标头重定向

问题描述 投票:0回答:1

我目前正在编写一个按需发行 JWT 令牌的应用程序。 颁发令牌后,用户应被重定向到网页。这就像一个魅力 - 但我需要为该重定向设置一个授权标头。

用户在网页 A 上输入其凭据。网页 A 向服务器 B 发送 POST 请求。服务器 B 检查凭据并提供令牌。现在用户应该被重定向到网页 C。

我尝试了以下方法:

@RequestMapping(value = "/token", method = RequestMethod.POST, produces = "application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<Object> token(
        @RequestParam("user") String _username, 
        @RequestParam("secret") String _secret
        ) throws Exception
{       
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("user", _username);
    map.add("secret", _secret);

    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map, headers);

    HttpStatus statusCode = HttpStatus.FOUND;
    HttpHeaders httpHeaders = new HttpHeaders();

    try {
        ResponseEntity<String> request = restTemplate.exchange(_url, HttpMethod.POST, entity, String.class);
    } catch (Exception ex) {
        ex.printStackTrance();
    }

    String response = request.getBody();

    JSONObject _tokenObject = new JSONObject(response);
    String _token = _tokenObject.getString("access_token");

    httpHeaders.add("Authorization", "Bearer: " + _token);

    URI _redirectUri = new URI("http://foo.example.com/webpageC");
    httpHeaders.setLocation(_redirectUri);

    return new ResponseEntity<>(httpHeaders, HttpStatus.FOUND);

}

重定向有效,但只有

/token
在重定向发生之前获取授权标头作为响应标头。

如何实现header发送到网页C?

谢谢。

更新

A

forward:
是不可能的,因为网页 C 位于另一个 URL 上并且不在同一个控制器中。

有人知道如何解决吗?

java spring redirect token jwt
1个回答
0
投票

通常,我们让前端开发人员处理重定向。如果您在后端工作,您可以提供一个 RESTful API 来发行 JwtToken。前端会关心接下来的重定向Http请求中如何携带Authorization header。这是一个简单的登录控制器,使用

mobile
password
来交换 JwtToken。

@RequestMapping(value = "/login", method = RequestMethod.POST)
public Result login(@RequestBody Map<String, String> loginMap) {
    User user = userService.findByMobile(mobile);

    if(user == null || !user.getPassword().equals(password)) {
        return new Result(ResultCode.MOBILEORPASSWORDERROR);
    }else {
        String token = jwtUtils.createJwt(user.getId(), user.getUsername(), map);
        return new Result(ResultCode.SUCCESS,token);
    }
}

如果您作为后端希望处理重定向,请将请求重定向到带有令牌作为参数的网页,在本例中:

GET http://www.example.com/login/success?token=xxx&redirectUrl=%2Fxxx

相关后端代码为:

    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Optional<String> redirectUri = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME)
            .map(Cookie::getValue);

    if(redirectUri.isPresent() && !isAuthorizedRedirectUri(redirectUri.get())) {
        throw new BadRequestException();
    }

    String targetUrl = redirectUri.orElse(getDefaultTargetUrl());

    String token = tokenProvider.createToken(authentication);

    return UriComponentsBuilder.fromUriString(targetUrl)
            .queryParam("token", token)
            .build().toUriString();
}

再次让前端将令牌放入进一步的请求中作为授权标头。

请记住,您正在返回响应,因此您可以设置响应标头。您无法为前端设置下一个请求的请求标头。

参考: https://www.callicoder.com/spring-boot-security-oauth2-social-login-part-2/

© www.soinside.com 2019 - 2024. All rights reserved.