赞
踩
1、加入jar
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
2、resource下yml文件添加
- # 安全认证的配置
- security:
- basic:
- enabled: false #是否生成随机密码
- user:
- name: root
- password: root
3、security账户密码加密类
- @Configuration
- public class SecurityConfig {
-
- @Bean
- public HttpHeaders getHeaders(){
- HttpHeaders headers = new httpHeaders();
- String auth = "root:root";
- byte[] encoderAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
- //此处注意Basic需要跟账号密码空格隔开
- String authHeader = "Basic " + new String(encoderAuth);
- headers.set("Authorization",authHeader);
- return headers;
- }
-
- @Bean
- public RestTemplate getRestTemplate(){
- return new RestTemplate();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
4、restController调用示例
- @RestController
- public class RestController {
-
- @Resource
- SecurityConfig securityConfig;
-
- @Resource
- HttpHeaders headers;
-
- @RequestMapping(value = "addDate",method = RequestMethod.POST)
- public Object addData(Dept dept){
- //exchange(urlm,请求方法,请求体参数(传入参数(可选),header体加密数据),映射对象)
- return securityConfig.getRestTemplate().exchange(url,HttpMethod.POST,new HttpEntity<Object>(dept,this.headers),Dept.class).getBody();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。