杂-spring-Security-RestTemplate

本文介绍如何使用Spring Security进行模拟登录,并解决了因Session ID变化导致的RESTful接口访问权限问题。文中提供了具体的代码示例,包括如何保留会话状态以及通过RestTemplate调用受保护的API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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());  //这个就是你接口返回的数据了


记录一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值