HTTP BASIC AUTHENTICATION by Java RestTemplate
今天在接入EMQX 管理架空API时,必须使用HTTP BASIC AUTHENTICATION。
对应的,我把日志打印出来:
RdeMacBook-Pro:~ r$ curl -v --basic -u username:password http://127.0.0.1:8081/hello/
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8081 (#0)
* Server auth using Basic with user 'username'
> GET /hello/ HTTP/1.1
> Host: 127.0.0.1:8081
> Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
> User-Agent: curl/7.63.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 29
< Date: Mon, 01 Apr 2019 12:05:47 GMT
<
hello world ! from port 8081
* Connection #0 to host 127.0.0.1 left intact
RdeMacBook-Pro:~ r$
发现,Http Header里有"Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=",其实是把username:password经过base64加密后得到:
RdeMacBook-Pro:~ r$ echo -n username:password | openssl base64
dXNlcm5hbWU6cGFzc3dvcmQ=
RdeMacBook-Pro:~ r$
在Java的实现,可以通过RestTemplateBuilder.basicAuthentication(username, password).build()获取对应的 RestTemplate:
@Component
public class EmqRestTemplateImplService {
@Value("${xh.im.mqtt.emq.http.username}")
private String emqUserName;
@Value("${xh.im.mqtt.emq.http.password}")
private String emqPassword;
@Autowired
public RestTemplateBuilder restTemplateBuilder;
@Bean("emqRestTemplate")
public RestTemplate getRestTemplate() {
return restTemplateBuilder.basicAuthentication(emqUserName, emqPassword).build();
}
}
使用方法:
@Service
public class EmqApiService {
@Autowired
public RestTemplate emqRestTemplate;
@Value("${xh.im.mqtt.emq.http.api.subscribe}")
private String emqSubscribeUrl;
public void setSubscription(List<String> topicList, Integer qos, String clientId) {
emqRestTemplate.postForEntity(this.emqSubscribeUrl, "", String.class);
}
}