JAVA 中 HTTP 基本认证(Basic Authentication)

服务端这么做

  1. 服务端告知客户端使用 Basic Authentication 方式进行认证
  2. 服务端接收并处理客户端按照 Basic Authentication 方式发送的数据

服务端告知客户端使用 Basic Authentication 方式进行认证

  • 服务端返回 401(Unauthozied)状态码给客户端
  • 服务端在Response 的 header “WWW-Authenticate” 中添加信息

在这里插入图片描述

服务端接收并处理客户端按照 Basic Authentication 方式发送的数据

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 方式向服务端发送数据

如果客户端是浏览器

浏览器支持 Basic Authentication 方式认证。浏览器会自动弹出提示窗体,并自动向该地址发送认证请求。

浏览器自动弹出的对话框:
在这里插入图片描述
点击“登录”后,浏览器自动向该地址发送请求:
在这里插入图片描述

  • 输入用户名: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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值