JAVA中HTTP基本認證(Basic Authentication)實現(xiàn)
什么是 HTTP 基本認證
HTTP 基本認證是一種簡單的認證方法??蛻舳丝梢酝ㄟ^用戶名和密碼進行認證。這些憑證以特定的格式在 Authorization HTTP Header 中發(fā)送。一般它以 Basic 關鍵字開始,后面是一個 base64 編碼的用戶名:密碼值。冒號字符在這里很重要。頭部應該嚴格遵循這個格式。
例如,要用 javanorth 用戶名和 http 密碼進行認證,我們必須發(fā)送這個 Header。
Basic amF2YW5vcnRoOmh0dHA=
我們可以通過使用 base64 解碼器和檢查解碼的結果來驗證。
服務端這么做
- 服務端告知客戶端使用 Basic Authentication 方式進行認證
- 服務端接收并處理客戶端按照 Basic Authentication 方式發(fā)送的數(shù)據(jù)
服務端告知客戶端使用 Basic Authentication 方式進行認證
- 服務端返回 401(Unauthozied)狀態(tài)碼給客戶端
- 服務端在Response 的 header “WWW-Authenticate” 中添加信息

服務端接收并處理客戶端按照 Basic Authentication 方式發(fā)送的數(shù)據(jù)
private boolean checkBasicAuthorization(HttpServletRequest request) {
String rawStringAuthorization = request.getHeader("Authorization");
Assert.isTrue(StringUtils.startsWith(rawStringAuthorization, "Basic"), "Basic 認證失敗");
String base64StringAuthorization = StringUtils.replaceOnce(rawStringAuthorization, "Basic", "");
base64StringAuthorization = StringUtils.trim(base64StringAuthorization);
byte[] bytesAuthorization = Base64Utils.decodeFromString(base64StringAuthorization);
String stringAuthorization = new String(bytesAuthorization);
String[] arrUserAndPass = StringUtils.split(stringAuthorization, ":");
Assert.isTrue(2==arrUserAndPass.length, "Basic 認證失敗");
String username = arrUserAndPass[0];
String password = arrUserAndPass[1];
if (StringUtils.equals(username, "myuser") && StringUtils.equals(password, "mypassword")) {
return true;
}
return false;
}
- org.apache.commons.lang3.StringUtils
- org.springframework.util.Base64Utils
客戶端這么做
客戶端按照 Basic Authentication 方式向服務端發(fā)送數(shù)據(jù)
如果客戶端是瀏覽器
瀏覽器支持 Basic Authentication 方式認證。瀏覽器會自動彈出提示窗體,并自動向該地址發(fā)送認證請求。
瀏覽器自動彈出的對話框:

點擊“登錄”后,瀏覽器自動向該地址發(fā)送請求:

- 輸入用戶名:
myuser,密碼:mypassword “bXl1c2VyOm15cGFzc3dvcmQ=”=base64("myuser:mypassword")
如果客戶端是 RestTemplat
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors()
.add(new BasicAuthenticationInterceptor("myuser","mypassword"));
;
return restTemplate;
}
}
如果客戶端是 HttpClient
略
其它
Basic Authentication 方式的認證,通常不需要登錄頁面,只需要登錄Action即可。

參考
https://developer.atlassian.com/server/jira/platform/basic-authentication/
到此這篇關于JAVA中HTTP基本認證(Basic Authentication)的文章就介紹到這了,更多相關JAVA HTTP基本認證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring?boot整合dubbo+zookeeper的詳細過程
本文講解Spring?Boot整合Dubbo與Zookeeper實現(xiàn)API、Provider、Consumer模式,包含依賴配置、啟動類注解、服務注冊與調用步驟,及QoS、超時、負載均衡等參數(shù)設置,確保分布式服務通信正常運行,感興趣的朋友一起看看吧2025-07-07

