authentication java_HTTP基本认证(Basic Authentication)的JAVA实例代码

本文介绍了HTTP基本认证的工作流程,并提供了一个使用Java实现的Servlet示例代码,展示了如何处理和验证客户端发送的Base64编码的用户名密码信息,以及在成功认证后如何利用session管理用户状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家在登录网站的时候,大部分时候是通过一个表单提交登录信息。

但是有时候浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证。

9236ac6131dd647f62495a06d32d395c.png

下面来看看一看这个认证的工作过程:

第一步:客户端发送http request 给服务器,服务器验证该用户是否已经登录验证过了,如果没有的话,

服务器会返回一个401 Unauthozied给客户端,并且在Response 的 header "WWW-Authenticate" 中添加信息。

如下图。

9b934504f9e0b5ed3ab2819a99e3de3c.png

ba3ed4b08f3bfd3daf6fdaf25219881f.png

第三步: 服务器将Authorization header中的用户名密码取出,进行验证, 如果验证通过,将根据请求,发送资源给客户端。

下面来看一个JAVA的示例代码

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Decoder;

public class HTTPAuthServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

String sessionAuth = (String) request.getSession().getAttribute("auth");

if (sessionAuth != null) {

System.out.println("this is next step");

nextStep(request, response);

} else {

if(!checkHeaderAuth(request, response)){

response.setStatus(401);

response.setHeader("Cache-Control", "no-store");

response.setDateHeader("Expires", 0);

response.setHeader("WWW-authenticate", "Basic Realm=\"test\"");

}

}

}

private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {

String auth = request.getHeader("Authorization");

System.out.println("auth encoded in base64 is " + getFromBASE64(auth));

if ((auth != null) && (auth.length() > 6)) {

auth = auth.substring(6, auth.length());

String decodedAuth = getFromBASE64(auth);

System.out.println("auth decoded from base64 is " + decodedAuth);

request.getSession().setAttribute("auth", decodedAuth);

return true;

}else{

return false;

}

}

private String getFromBASE64(String s) {

if (s == null)

return null;

BASE64Decoder decoder = new BASE64Decoder();

try {

byte[] b = decoder.decodeBuffer(s);

return new String(b);

} catch (Exception e) {

return null;

}

}

public void nextStep(HttpServletRequest request, HttpServletResponse response) throws IOException {

PrintWriter pw = response.getWriter();

pw.println(" next step, authentication is : " + request.getSession().getAttribute("auth") + "
");

pw.println("
");

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

doGet(request, response);

}

}

当request第一次到达服务器时,服务器没有认证的信息,服务器会返回一个401 Unauthozied给客户端。

认证之后将认证信息放在session,以后在session有效期内就不用再认证了。

以上就是小编为大家带来的HTTP基本认证(Basic Authentication)的JAVA实例代码全部内容了,希望大家多多支持脚本之家~

以下是Java发送带Basic Auth认证HTTP POST请求的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; public class HttpPostWithBasicAuth { public static void main(String[] args) throws IOException { String url = "http://example.com/api/resource"; String username = "myusername"; String password = "mypassword"; String postData = "param1=value1&param2=value2"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // set request method con.setRequestMethod("POST"); // set basic authentication header String auth = username + ":" + password; byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8)); String authHeaderValue = "Basic " + new String(encodedAuth); con.setRequestProperty("Authorization", authHeaderValue); // set post data con.setDoOutput(true); con.getOutputStream().write(postData.getBytes("UTF-8")); // get response int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print response System.out.println("Response code: " + responseCode); System.out.println("Response body: " + response.toString()); } } ``` 在上面的代码中,我们使用 `HttpURLConnection` 类来建立HTTP连接,并设置了请求头中的基本认证信息。我们还设置了POST数据,并获取了响应,最后打印了响应码和响应体。请注意,此示例仅用于演示目的,实际使用中需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值