Basic协议认证原理和实现

1、Basic协议认证概述

在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份证的方法,当一个客户端向HTTP服务器进行数据请求时,如果客户端未被认证,则HTTP服务器将通过基本认证过程对客户端的用户名及密码进行验证,以决定用户是否合法。客户端在接收到HTTP服务器的身份认证要求后:会提示用户输入用户名及蜜码.然后将用户名及密码以BASE64加密;

加蜜后的密文将附加于请求信息史:如当用户名为admin,密码为:123456时,客户端将用户名和密码用“:”合并,并将合并后的字符串用BASE64加密为密文,并于每次请求数据时,将密文附加于请求头(Request Header)中。HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64加密的用户名和密码),解开请求包,对用户名及密码进行验证,如果用户名及密码正确,则根据客户端请求,返回客户端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。

2、post模拟请求

3、拦截器判断

 

package com.shucha.deveiface.web.interceptor;


import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class OpenApiInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");

        // 1、通过用户名和密码编码比对
        String userName = "admin";
        String passWord = "123456";
        //编码
        String message = userName + ":" + passWord;
        String encode = Base64.getEncoder().encodeToString(message.getBytes(StandardCharsets.UTF_8));  // 方式一
        if(authorization.equals(encode)) {
            return true;
        }

        // 2、通过解码获取的authorization
        //数据解密
        String oldMsg = new String(Base64.getDecoder().decode(authorization));
        if(oldMsg != null && oldMsg != "") {
            oldMsg = oldMsg.replace("Basic ","");
            String userName1 = oldMsg.split(":")[0];
            String passWord1 = oldMsg.split(":")[1];
        }
}

4、Base64Data 编码解码

package com.shucha.deveiface.biz.test;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author tqf
 * @Description Basic协议 加密获得Authorization
 * @Version 1.0
 * @since 2022-08-15 16:09
 */
public class Base64Data {
    public static void main(String[] args) {
        base64Data();
    }

    public static void base64Data() {
        String userName = "admin";
        String passWord = "123456";
        //数据编码
        String message = userName + ":" + passWord;
        String encode = Base64.getEncoder().encodeToString(message.getBytes(StandardCharsets.UTF_8));  // 方式一
        String encode2 = new String(Base64.getEncoder().encode(message.getBytes()), StandardCharsets.UTF_8);  // 方式二
        System.out.println(encode);
        System.out.println(encode2);

        //数据解码
        String oldMsg = new String(Base64.getDecoder().decode(encode));
        System.out.println(oldMsg);
    }
}
经验分享 程序员 微信小程序 职场和发展