杂-spring-Security-RestTemplate

来源:互联网 发布:吉布提保障基地知乎 编辑:程序博客网 时间:2024/06/08 01:31

用Security模拟登陆,

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("用户名", "密码");//当然你也可以去继承来实现自己的东西,详情自己去查Authentication authentication = authenticationManager.authenticate(authRequest);SecurityContext securityContext = SecurityContextHolder.createEmptyContext();securityContext.setAuthentication(authentication);


说一下平时遇到的小问题,在开发过程中,不下总登陆,但是又登陆又没权限去调restFul接口,这个很烦。于是就去看了一下系统的权限,就是上面的spring-Security,所以我就去弄了上面的代码,但是还是不行。通过查资料,了解到每次登陆或者不登陆系统都给浏览器一个cookies 里面赛了个sessionID,要是这个id变了或者不存在,就是非法登陆什么的。所以,上面那段代码只是一个口令而已,还是没有session。

本人懒又想导入apche的httpclient,还是用了RestTemplate,

一点点代码:

RestTemplate restTemplate = new RestTemplate();        Cookie[] cookies =  request.getCookies();//这个是HttpServletRequest, 反正你拿得到你系统给的cookies就行了,丢到headers        String cookieHeader = cookies[0].getName()+"="+cookies[0].getValue();        HttpHeaders headers = new HttpHeaders();        headers.add("Cookie", cookieHeader );        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/api/v3/*****/list/standard?page_no=1&page_size=10&os=&ls=&ds=&pl=&q=&page_sort=activedAt_asc",                HttpMethod.GET,                new HttpEntity<String>(headers),                String.class);
logger.error( response.getBody());  //这个就是你接口返回的数据了


记录一下

原创粉丝点击