Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send received jsessionid via spring 4 resttemplate

I'm writing an messenger with JavaFX and Spring4 on client-site and Spring4 on server-site. I secured the server with spring-security 3.2. Now my Problem: I have a loginpage on the client witch sends the login information to spring-security and receive the JSESSIONID cookie. This works fine but when I try to send the JSESSIONID with my request I become an

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class org.messenger.rest.JSONConversationResult] and content type [text/html;charset=UTF-8]

Server Inizializer

public class SpringMvcInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {ApplicationConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] {WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
}

Server SecurityInizializer

public class SpringSecurityInitializer extends
    AbstractSecurityWebApplicationInitializer {
}

Server SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DriverManagerDataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String authQuery = "select userid, authority from user where userid = ?";
        String userQuery = "select userid, pw, enabled from user where userid = ?";

        auth.jdbcAuthentication().dataSource(dataSource)
            .passwordEncoder(passwordEncoder())
            .usersByUsernameQuery(userQuery)
            .authoritiesByUsernameQuery(authQuery);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http
            .authorizeRequests()
                .antMatchers("/register").permitAll()
                .antMatchers("/getconvs", "/getcontacts").hasRole("USER")
                .and()
            .formLogin()
                .and()
            .csrf().disable();
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new de.daschner.messenger.security.AuthenticationEntryPoint();
    }

    @Bean
    public SuccessHandler successHandler() {
        return new SuccessHandler();
    }

    @Bean
    public SimpleUrlAuthenticationFailureHandler failureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(11);
    }
}

Server requestmapping for the secured "page"

@RequestMapping(value="/getconvs", method={RequestMethod.GET},
        produces={MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody JSONConversationResult getConvsList(HttpServletRequest request, @RequestParam(value="uid") String uid){
    JSONConversationResult ret = new JSONConversationResult();
    Map<String, Map<Date, String>> convs = convService.getConvsList(uid);
    if (convs != null) {
        ret.setConversations(convs);
        ret.setMessage("OK");
        ret.setError(0);
    } else {
        ret.setError(1);
        ret.setMessage("Verbindungsfehler");
    }
    return ret;
}

Client send Login and get Cookie

    Map<String, String> loginform = new HashMap<String, String>();
    loginform.put("username", user);
    loginform.put("password", pw);
    HttpEntity<Map<String, String>> login = new HttpEntity<Map<String, String>>(loginform);

    ResponseEntity<HttpServletResponse> response = restTemplate.exchange(
            "http://localhost:8080/messenger-webapp/login", 
            HttpMethod.POST, 
            login, 
            HttpServletResponse.class);

    HttpHeaders headers = response.getHeaders();
    Set<String> keys = headers.keySet();
    String cookie = "";
    for (String header : keys) {
        if (header.equals("Set-Cookie")) {
            cookie = headers.get(header).get(0);
        }
    }
    String jsessionid = cookie.split(";")[0];
    conf.setJsessionid(jsessionid.split("=", 2)[1]);
    return ret;

Client send JSESSIONID with request

    ResponseEntity<JSONConversationResult> response = restTemplate.exchange(
            "http://localhost:8080/messenger-webapp/getconvs?uid=" + uid, 
            HttpMethod.GET, 
            getAuthHeader(), 
            JSONConversationResult.class);

    JSONConversationResult ret = response.getBody();
    return ret;

    private HttpEntity<String> getAuthHeader() {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Cookie", "JSESSIONID=" + config.getJsessionid());
        return new HttpEntity<String>(requestHeaders);
    }

I hope you can help me.

EDIT:

Ok I figured out that the problem was not that the JSESSIONID wasn't sent correctly. But my login was incorrect and my query to get the user from database.

The correct login-post

ClientHttpResponse response = restTemplate.execute(
            "http://localhost:8080/messenger-webapp/login",
            HttpMethod.POST,
            new RequestCallback() {

                @Override
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    request.getBody().write(("username=" + user + "&password=" + pw).getBytes());
                }
            },
            new ResponseExtractor<ClientHttpResponse>() {

                @Override
                public ClientHttpResponse extractData(ClientHttpResponse response)
                        throws IOException {
                    return response;
                }
            });

The correct query

String authQuery = "select u.userid, r.role_name from user u, role r, user_role a where u.dbid = a.user_id and r.dbid = a.role_id and u.userid = ?";

I hope this will help other people. If anyone has an alternative please let me know.

like image 883
Bloodline Avatar asked Jun 27 '14 07:06

Bloodline


1 Answers

Ok I figured out that the problem was not that the JSESSIONID wasn't sent correctly. But my login was incorrect and my query to get the user from database.

The correct login-post

ClientHttpResponse response = restTemplate.execute(
            "http://localhost:8080/messenger-webapp/login",
            HttpMethod.POST,
            new RequestCallback() {

                @Override
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    request.getBody().write(("username=" + user + "&password=" + pw).getBytes());
                }
            },
            new ResponseExtractor<ClientHttpResponse>() {

                @Override
                public ClientHttpResponse extractData(ClientHttpResponse response)
                        throws IOException {
                    return response;
                }
            });

The correct query

String authQuery = "select u.userid, r.role_name from user u, role r, user_role a where u.dbid = a.user_id and r.dbid = a.role_id and u.userid = ?";

I hope this will help other people. If anyone has an alternative please let me know.

like image 91
Bloodline Avatar answered Sep 23 '22 12:09

Bloodline