HTTP認證
阿新 • • 發佈:2021-10-11
1.開啟外掛
HTTP 認證使用外部自建 HTTP 應用認證資料來源,根據 HTTP API 返回的資料判定認證結果,能夠實現複雜的認證鑑權邏輯。啟用該功能需要將 emqx_auth_http 外掛啟用,並且修改該外掛的配置檔案,在裡面指定HTTP認證介面的url。 emqx_auth_http 外掛同時還包含了ACL的功能,我們暫時還用不上,通過註釋將其禁用。 1:在Dashboard中中開啟 emqx_auth_http 外掛,同時為了避免誤判我們可以停止通過username,clientID 進行認證的外掛 emqx_auth_clientid , emqx_auth_username2.認證原理
- 認證失敗:API 返回 4xx 狀態碼
- 認證成功:API 返回 200 狀態碼
- 忽略認證:API 返回 200 狀態碼且訊息體 ignore
3.HTTP請求資訊
# etc/plugins/emqx_auth_http.conf ## 重試設定 auth.http.request.retry_times = 3 auth.http.request.retry_interval = 1s auth.http.request.retry_backoff = 2.0 4.認證請求
5.認證服務開發
建立基於springboot2.3.0.RELEASE的應用程式: emq-demo 1.pom.xml<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot=starter-wen</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.建立application.yml
server:
port: 8991
spring:
application:
name: emq-demo
3.建立Controller:AuthController
@RestController
@RequestMapping("/mqtt")
public class AuthController {
private static final Logger log = LoggerFactory.getLogger(AuthController.class);
private HashMap<String,String> users;
@PostConstruct
public void init(){
users = new HashMap<>();
users.put("user","123456");
users.put("emq-client2","123456");
users.put("emq-client3","123456");
}
@PostMapping("/auth")
public ResponseEntity auth(@RequestParam("clientid") String clientid,
@RequestParam("username") String username,
@RequestParam("password") String password){
log.info("emqx http認證元件開始呼叫任務服務完成認證,clientid={},username={},password={}",clientid,username,password);
String value = users.get(username);
if(StringUtils.isEmpty(value)){
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
if(!value.equals(password)){
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity(HttpStatus.OK);
}
}
6.MQTTX客戶端驗證
這個地方的Client-ID隨便輸入,因為在驗證的程式碼裡沒有對該欄位做校驗,之後點連線,發現會連線成功,然後可以去自定義的認證服務中檢視控制檯輸出,證明基於外部的http驗證介面生效了。在實際專案開發過程中,HTTP介面校驗的程式碼不會這麼簡單,賬號和密碼之類的資料肯定會存在後端資料庫中,程式碼會通過傳入的資料和資料庫中的資料做校驗,如果成功才會校驗成功,否則校驗失敗。 當然EMQ X除了支援我們之前講過的幾種認證方式外,還支援其他的認證方式,比如:MySQL認證、PostgreSQL認證、Redis認證、MongoDB認證,對於其他這些認證方式只需要開啟對應的EMQ X外掛並且配置對應的配置檔案,將對應的資料儲存到相應的資料來源即可。