今天在接入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);
}
}