我正在构建一个restful身份验证服务,但在连接它时遇到了问题。在尝试检索响应时,我得到了可怕的“服务器返回http响应代码:400”。这看起来很奇怪。我想我在发送请求时会收到这个错误。
我将此服务用作Spring安全身份验证提供程序的一部分。我目前使用的是模拟器,而不是实际的测试服务。它不会连接到模拟器或服务。
以下是调用方法:

public <T> T invoke(String service, Object request, Class<T> responseType) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    URL url = new URL("http://localhost:8888/simulator/rest" + service);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();

    uc.setRequestMethod("POST");
    uc.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    uc.setDoOutput(true);
    uc.setDoInput(true);
    uc.connect();

    OutputStream out = uc.getOutputStream();
    mapper.writeValue(out, request);
    out.close();

    return mapper.readValue(uc.getInputStream(), responseType);
}

下面是调用此方法的代码:
UsernamePasswordAuthenticationToken token =
    new UsernamePasswordAuthenticationToken("thomas", "thomas");
UsernamePasswordAuthenticationToken response =
    invoke("/authenticate", token, UsernamePasswordAuthenticationToken.class);

以下是调用的模拟器方法:
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@ResponseBody
public UsernamePasswordAuthenticationToken authenticate(
    @RequestBody UsernamePasswordAuthenticationToken userNameAndPassword) {

    String userName = (String) userNameAndPassword.getPrincipal();
    String password = (String) userNameAndPassword.getCredentials();
    if (userName.equalsIgnoreCase("thomas")) {
        if (userName.equals(password)) {
            UsernamePasswordAuthenticationToken response =
                new UsernamePasswordAuthenticationToken(
                    userName,
                        password,
                        new ArrayList<GrantedAuthority>());
                return response;
            }
        }
        return new UsernamePasswordAuthenticationToken(userName, password);
    }

导致错误的行是:
mapper.readValue(uc.getInputStream(), responseType);

如果看不到这段代码的任何问题。一定看得太久了。需要重新审视这个问题。
顺便说一下,这个rest服务和模拟器已经成功地用于其他操作。
其他信息:
错误发生在uc.getinputstream()调用中。httpurlconnection.inputstream=null。
此外,请求的标题如下:
如果这有帮助,以下是此请求的标题:
[WARN] 400 - POST /simulator/rest/authenticate (127.0.0.1) 1417 bytes
   Request headers
      Content-Type: application/json;charset=UTF-8
      X-Tenant: 1
      Authorization: 0000013770b132a1dfcbfe0a694542b244534e0e406cfa857660c904daa89af91d0ac769
      Cache-Control: no-cache
      Pragma: no-cache
      User-Agent: Java/1.6.0_26
      Host: localhost:8888
      Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
      Connection: keep-alive
      Content-Length: 112
   Response headers
      Set-Cookie: JSESSIONID=1r02p7yvm8mzs;Path=/
      X-UA-Compatible: IE=9
      Content-Type: text/html; charset=iso-8859-1
      Content-Length: 1417

这是我的代币代码:
import java.util.List;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

public class SerializedAuthenticationToken extends UsernamePasswordAuthenticationToken {
    private static final long serialVersionUID = 2783395505630241326L;

    private Object principal;
    private Object credentials;

    /**
     * no-arg constructor to satisfy Serializable.
     */
    public SerializedAuthenticationToken() {
        super(null, null);
    }

    /**
     * constructor.
     */
    public SerializedAuthenticationToken(Object principal, Object credentials) {
        super(null, null);
        setPrincipal(principal);
        setCredentials(credentials);
    }

    /**
     * constructor with List<GrantedAuthorities>.
     */
    public SerializedAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities) {
        super(null, null, authorities);
        setPrincipal(principal);
        setCredentials(credentials);
    }

    public Object getPrincipal() {
        return principal;
    }

    public void setPrincipal(Object principal) {
        this.principal = principal;
    }

    public Object getCredentials() {
        return credentials;
    }

    public void setCredentials(Object credentials) {
        this.credentials = credentials;
    }

    public void setName(Object name) {

    }
}

我现在也得到了一个新的堆栈跟踪:
org.codehaus.jackson.map.JsonMappingException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead (through reference chain: com.mckesson.shared.util.SerializedAuthenticationToken["authenticated"])

最佳答案

你需要创建一个虚拟令牌来实现这一点。这是我的测试来验证它:

public class JacksonTest {

@Test
public void test() throws Exception {

    ObjectMapper mapper = new ObjectMapper();

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("thomas", "thomas");
    String tokenStr = mapper.writeValueAsString(token);
    /* WON'T WORK
     UsernamePasswordAuthenticationToken auth = mapper.readValue(tokenStr, UsernamePasswordAuthenticationToken.class);
     */
    MyToken auth = mapper.readValue(tokenStr, MyToken.class);
    String authStr = mapper.writeValueAsString(auth);

    Assert.assertThat(tokenStr.equals(authStr), is(true));
}


private static class MyToken extends UsernamePasswordAuthenticationToken {
    private Object principal;
    private Object credentials;

    private static final long serialVersionUID = -5045038656629236029L;

    public MyToken() {

        super(null, null);
    }

    public MyToken(Object principal, Object credentials) {

        super(null, null);
        this.principal = principal;
        this.credentials = credentials;
    }

    /**
     * @return the principal
     */
    public Object getPrincipal() {
        return principal;
    }

    /**
     * @param principal the principal to set
     */
    public void setPrincipal(Object principal) {
        this.principal = principal;
    }

    /**
     * @return the credentials
     */
    public Object getCredentials() {
        return credentials;
    }

    /**
     * @param credentials the credentials to set
     */
    public void setCredentials(Object credentials) {
        this.credentials = credentials;
    }


    public void setName(Object name) {

    }

}

}

08-06 06:02
查看更多