Spring Boot - 开启 HttpBasic 认证方式

文章目录

  • 思路
  • 实践
    • 环境
    • 新建项目
    • 测试
  • 参考

思路

想要开启 HttpBasic 认证方式,服务器需要设置响应头 WWW-Authenticate: Basic realm="Realm"。当客户端(浏览器)访问指定的 URL,就会触发 HttpBasic 认证方式:

Spring Boot - 开启 HttpBasic 认证方式_第1张图片

当用户在 Sign in 对话框中输入用户名和密码,点击 Sign in 按钮之后,浏览器使用 Base64 对用户名和密码进行编码,然后将其放在 Authorization 请求头中发送给服务器:

注意:因为浏览器使用 Base64 对用户名和密码进行编码,因此,一旦 Authorization 请求头中的内容被截获,将导致用户名和密码泄露。

Spring Boot - 开启 HttpBasic 认证方式_第2张图片

实践

环境

集成开发环境:

Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750
OS: Windows 10, v.10.0, x86_64 / win32

新建项目

新建 Spring Starter Project,其结构如下:

Spring Boot - 开启 HttpBasic 认证方式_第3张图片

编辑 pom.xml 依赖配置文件,主要引入:

  • spring-boot-starter-web
  • fastjson

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>
	
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.6.2version>
		<relativePath/> 
	parent>
	
	<groupId>com.mkgroupId>
	<artifactId>demoartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>demoname>
	<description>Demo project for Spring Bootdescription>
	
	<properties>
		<fastjson.version>1.2.8fastjson.version>
		<java.version>1.8java.version>
	properties>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-devtoolsartifactId>
			<scope>runtimescope>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-configuration-processorartifactId>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
		
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>${fastjson.version}version>
        dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombokgroupId>
							<artifactId>lombokartifactId>
						exclude>
					excludes>
				configuration>
			plugin>
		plugins>
	build>
project>

新建一个 HelloController 控制器,方法 login 的主要作用是判断客户端是否提供 Authorization 请求头,如果没有,设置响应状态码为 401,并设置响应头 WWW-Authenticate: Basic realm="Realm",要求客户端使用 HttpBasic 认证方式进行认证:

package com.mk.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

import org.springframework.http.HttpStatus;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class HelloController {

	private static final ObjectMapper objectMapper = new ObjectMapper();
	
	
	@GetMapping(path = "login")
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		String authorization = request.getHeader("Authorization");
		System.out.println("Authorization: " + authorization);
		
		if (authorization == null) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.setHeader("WWW-Authenticate", "Basic realm=\"Realm\"");
		} else {
			String credentials = authorization.substring("Basic ".length());
			byte[] decodedCredentials = Base64Utils.decode(credentials.getBytes("UTF-8"));
			System.out.println("Decoded Credentials: " + new String(decodedCredentials));
			
			response.setStatus(HttpStatus.OK.value());
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			
			Map<String, Object> result = new HashMap<>();
			result.put("message", HttpStatus.OK.name());
			result.put("ip", request.getRemoteAddr());
			result.put("credentials", new String(decodedCredentials));
			
			PrintWriter writer = response.getWriter();
			writer.write(objectMapper.writeValueAsString(result));
			writer.flush();
			writer.close();
		}
	}
}

测试

运行该项目,当用户使用浏览器访问 http://localhost:8080/login,并提交用户名和密码之后(此处我输入的用户名:user,密码:123),控制台输出:

Authorization: Basic dXNlcjoxMjM=
Decoded Credentials: user:123

参考

Web technology for developers > HTTP > HTTP headers > WWW-Authenticate

Web technology for developers > HTTP > HTTP authentication

Web technology for developers > HTTP > HTTP headers > Authorization

你可能感兴趣的:(Spring,Boot,http,spring,boot,http,basic)