SpringCloud Security 安全认证

1、加入jar


	org.springframework.boot
	spring-boot-starter-security

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();
    }
}

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(dept,this.headers),Dept.class).getBody();
    }
} 
  

SpringCloud Security 安全认证_第1张图片 

 

你可能感兴趣的:(#,springCloud,spring)