What was I wrong when using Jersey Client to authenticate an Spring Security web application?

177 views Asked by At

I have a web application which is protected by Spring Security Login Form authentication. Now I want to use Jersey Client to authenticate to my web pages and I think I should pass through login form as I do on a normal browser.

My client authentication code is as below

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:8080/authentication-inmem/j_spring_security_check");
    Form form = new Form();
    form.param("j_username", "car");
    form.param("j_password", "scarvarez");

    Response response =  target.request()
    .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    System.out.println(response.getStatus());

This code always produces 404 status code. When I type the link http://localhost:8080/authentication-inmem/j_spring_security_check to my browser or just modify above code to an GET request. I could normally receive HTML code for authentication login form. Hence, I really don't know why this url is not found with an POST?

Hope you could show me what I am wrong here, and moreover, what I am doing is a proper way to authenticate to my server without using a browser?

1

There are 1 answers

0
Chiến Nghê On BEST ANSWER

I have found the answer, by default Jersey client will automatically redirect as soon as it receives a response with status is 3xx. (in this case it is 302). Now, just turn off the feature by a bit configuration ahead, and I could get the status 302 display on my console.

ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, false);
Client client = ClientBuilder.newClient(clientConfig);