java http auth bpn_Http basic Auth 认证方式帮助类

这是一个Java类,用于实现HTTP Basic Auth认证。它包含了检查请求头中的授权信息、解码Base64编码的认证字符串、MD5加密以及处理未授权响应的功能。该类依赖于Spring的@Component注解和SysUserService来获取用户信息。
摘要由CSDN通过智能技术生成

importjava.io.IOException;importjava.security.MessageDigest;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.lang.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;importcn.evun.tms.common.dto.LoginSysUser;importcn.evun.tms.system.service.SysUserService;import sun.misc.*;/*** basic Auth 认证方式

*

*@authorGeely

**/@Componentpublic classBasicAuthenticationUtil {

@AutowiredprivateSysUserService sysUserService;/***

*@paramrequest

*@paramresponse

*@paramsessionName

*@return

*/

public booleancheckHeaderAuth(HttpServletRequest request, String sessionName) {

String authorization= request.getHeader("Authorization");if (StringUtils.isBlank(authorization) || authorization.length() < 6) {return false;

}

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

String decodedAuth=base64Decode(authorization);if (decodedAuth == null || "".equals(decodedAuth)) {

decodedAuth= "";

}

String[] useAuth= decodedAuth.split(":");if (useAuth.length < 2) {return false;

}

LoginSysUser sysUser= sysUserService.getUserByLogin(useAuth[0], encoderByMd5(useAuth[1]));if (sysUser == null) {return false;

}if(StringUtil.isNotBlank(sessionName)) {

request.getSession().setAttribute(sessionName, decodedAuth);

}return true;

}/***

*@paramrequest

*@paramresponse

*@paramsessionName

*@return

*/

public booleancheckUserAuth(HttpServletRequest request, String sessionName) {

String sessionAuth= null;if(StringUtil.isNotBlank(sessionName)) {

sessionAuth=(String) request.getSession().getAttribute(sessionName);if (sessionAuth == null || "".equals(sessionAuth)) {return false;

}

String[] useAuth= sessionAuth.split(":");if (useAuth.length < 2) {return false;

}else{

LoginSysUser sysUser= sysUserService.getUserByLogin(useAuth[0], encoderByMd5(useAuth[1]));if (sysUser != null) {return true;

}

}return false;

}return true;

}public static voidredirect(HttpServletResponse response) {

response.setStatus(401);

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

response.setDateHeader("Expires", 0);

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

}/*** 编码

*

*@parambstr

*@returnString*/@SuppressWarnings("restriction")public static String base64Encode(byte[] bstr) {

String strEncode= newBASE64Encoder().encode(bstr);returnstrEncode;

}/*** 解码

*

*@paramstr

*@return

*/@SuppressWarnings("restriction")public staticString base64Decode(String str) {if(StringUtil.isBlank(str)) {return null;

}

String s= null;try{

BASE64Decoder decoder= newBASE64Decoder();byte[] b =decoder.decodeBuffer(str);

s= new String(b, "UTF8");

}catch(IOException e) {

s= null;

}returns;

}/*** 对字符串md5加密(大写+数字)

*

*@paramstr

* 传入要加密的字符串

*@returnMD5加密后的字符串*/

public staticString encoderByMd5(String s) {char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

String strMd5= null;try{byte[] bt = s.getBytes("UTF8");//获得MD5摘要算法的 MessageDigest 对象

MessageDigest md = MessageDigest.getInstance("MD5");//使用指定的字节更新摘要

md.update(bt);//获得密文

byte[] mdt =md.digest();//把密文转换成十六进制的字符串形式

int j =mdt.length;char str[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 =mdt[i];

str[k++] = hexDigits[byte0 >>> 4 & 0xf];

str[k++] = hexDigits[byte0 & 0xf];

}

strMd5= newString(str).toLowerCase();

}catch(Exception e) {

strMd5= null;

}returnstrMd5;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是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、付费专栏及课程。

余额充值