Spring-Security:使用登录时返回的cookie访问安全资源

时间:2015-07-01 12:21:40

标签: java spring cookies spring-security resttemplate

我正在研究Java桌面应用程序,经过一些搜索后,我能够使用RestTemplate对用户进行身份验证。现在的情况是我在桌面端有cookie String(下面给出的代码)。现在我想做的是做两件重要的事情,让用户使用该cookie登录,以及访问(GET,POST,DELETE)安全资源,这些资源标有@Secured或@PreAuthorize注释。

这是我的验证码:

   @Override
    public void initialize(URL location, ResourceBundle resources) {
        submitButton.setOnAction(event -> {
           if(!(usernameField.getText().isEmpty() && passwordField.getText().isEmpty())){
               try {
                   RestTemplate rest = new RestTemplate();
                   String jsessionid = rest.execute("http://localhost:8080/j_spring_security_check", HttpMethod.POST,
                           new RequestCallback() {
                               @Override
                               public void doWithRequest(ClientHttpRequest request) throws IOException {
                                   request.getBody().write(("j_username=" + usernameField.getText() + "&j_password=" + passwordField.getText()).getBytes());
                               }
                           }, new ResponseExtractor<String>() {
                               @Override
                               public String extractData(ClientHttpResponse response) throws IOException {
                                   List<String> cookies = response.getHeaders().get("Cookie");

                                   // assuming only one cookie with jsessionid as the only value
                                   if (cookies == null) {
                                       cookies = response.getHeaders().get("Set-Cookie");
                                   }

                                   String cookie = cookies.get(cookies.size() - 1);
                                   System.out.println("Cookie is "+cookie);
                                   int start = cookie.indexOf('=');
                                   int end = cookie.indexOf(';');

                                   return cookie.substring(start + 1, end);
                               }
                           });

              //   rest.put("http://localhost:8080/rest/program.json;jsessionid=" + jsessionid, new DAO("REST Test").asJSON());

               } catch (AuthenticationException e) {
                   System.out.println("AuthenticationException");
               }
           } else {
               System.out.println("Fields are empty");
           }
        });
    }

计划的输出是:

DEBUG: org.springframework.web.client.RestTemplate - Created POST request for "http://localhost:8080/j_spring_security_check"
DEBUG: org.springframework.web.client.RestTemplate - POST request for "http://localhost:8080/j_spring_security_check" resulted in 302 (Found)
Cookie is JSESSIONID=903B2924CCC84421931D52A4F0AA3C7E; Path=/; HttpOnly

如果我在服务器端,我会简单地调用以下方法来获取当前经过身份验证的用户:

 @Override
    public Person getCurrentlyAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }

如何在基于桌面的Java应用程序上获取当前身份验证用户,以便我可以使用以下方法并在桌面java应用程序上进行身份验证。 :

Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        Authentication authentication = new UsernamePasswordAuthenticationToken(person1, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);

这样,我也可以将@Secured注释用于桌面java应用程序。非常感谢。

更新

所以在服务器端我创建了一个方法,它为我提供了登录用户。正如答案中所建议的,我可以使用相同的休息模板,但我想将cookie存储在用户本地数据库中,而不是在用户点击此处和那里时传递Resttemplates对象。

服务器端方法:

@Secured("ROLE_USER")
@RequestMapping(value = "/rest/getloggedinuser", method = RequestMethod.GET)
public
@ResponseBody
ResponseEntity<RestPerson> getLoggedInRestUser() {
    Person person = this.personService.getCurrentlyAuthenticatedUser();
    RestPerson restPerson = new RestPerson();
    restPerson.setFirstname(person.getFirstName());
    restPerson.setUsername(person.getUsername());
    restPerson.setPassword("PROTECTED");
    return new ResponseEntity<RestPerson>(restPerson, HttpStatus.OK);
}

现在,接下来,我现在尝试使用相同的RestTemplate检查此方法是否适用于下面的代码,但我真的想知道如何只使用cookie来实现此目的:

 HttpHeaders requestHeaders = new HttpHeaders();
                                   requestHeaders.add("Cookie", cookie);
                                   HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
                                   ResponseEntity rssResponse = rest.exchange(
                                           "/rest/getloggedinuser",
                                           HttpMethod.GET,
                                           requestEntity,
                                           Person.class);
                                   String rssResponseBody = (String)rssResponse.getBody();
                                   System.out.println("Response body is ");

有没有办法将ResponseBody中的Object强制转换为Person对象???

1 个答案:

答案 0 :(得分:0)

  1. 如果您想获得存储在服务器端的一些用户信息,您应该创建一个新服务,例如服务器上的“getUserInformation”,它将提供此类信息。
  2. 您不应手动提取Cookie,只需重复使用相同的RestTemplate,它会在内部存储Cookie(特别是在底层的HttpClient中)。这就是你如何获得安全资源。
  3. <强>更新

    您不需要传递RestTemplate,只需将其设为单例并在任何地方使用它。

    rssResponse.getBody();应该返回一个Person对象,而不是String。

相关问题