当前位置:   article > 正文

Spring Boot - 开启 HttpBasic 认证方式_springboot3 httpbasic认证

springboot3 httpbasic认证

思路

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

在这里插入图片描述

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

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

在这里插入图片描述

实践

环境

集成开发环境:

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

新建项目

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

在这里插入图片描述

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

  • spring-boot-starter-web
  • fastjson
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
	
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	
	<groupId>com.mk</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	
	<properties>
		<fastjson.version>1.2.8</fastjson.version>
		<java.version>1.8</java.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

新建一个 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();
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

测试

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

Authorization: Basic dXNlcjoxMjM=
Decoded Credentials: user:123
  • 1
  • 2

参考

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

Web technology for developers > HTTP > HTTP authentication

Web technology for developers > HTTP > HTTP headers > Authorization

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/256409
推荐阅读
相关标签
  

闽ICP备14008679号