概述
在 spring security 框架中,authenticationmanager 接口扮演着核心角色,负责处理认证请求并决定用户身份是否合法。本文将详细讲解这一接口的工作原理、应用场景,并结合 spring boot 3.4.3 版本提供实战示例。
authenticationmanager 接口概述
authenticationmanager 是 spring security 认证体系的核心接口,位于 org.springframework.security.authentication 包下,其定义非常简洁:
public interface authenticationmanager {
authentication authenticate(authentication authentication)
throws authenticationexception;
}该接口仅包含一个方法 authenticate(),用于处理认证请求,其工作流程如下:
- 接收一个
authentication对象作为参数,该对象包含用户提交的认证信息(如用户名 / 密码) - 执行认证逻辑
- 认证成功时,返回一个包含完整用户信息和权限的
authentication对象 - 认证失败时,抛出
authenticationexception异常
核心实现类
在实际应用中,我们通常不会直接实现 authenticationmanager 接口,而是使用其现成的实现类:
providermanager:
- 最常用的实现类
- 委托一个或多个
authenticationprovider实例处理认证请求 - 支持多种认证机制并存
authenticationprovider:
- 不是
authenticationmanager的实现类,而是由providermanager调用 - 每个
authenticationprovider处理特定类型的认证请求
- 不是
daoauthenticationprovider:
- 常用的
authenticationprovider实现 - 通过
userdetailsservice获取用户信息并验证密码
- 常用的
工作原理
authenticationmanager 的认证流程可概括为:
- 客户端提交认证信息(如用户名 / 密码)
- 认证信息被封装成
authentication对象 authenticationmanager接收该对象并调用authenticate()方法providermanager会遍历其配置的authenticationprovider列表- 找到支持当前
authentication类型的authenticationprovider并委托其进行认证 - 认证成功后,返回包含完整信息的
authentication对象 - 认证结果被 securitycontext 存储,用于后续的授权判断
应用场景
authenticationmanager 适用于各种需要身份认证的场景:
- 表单登录认证:处理用户名 / 密码登录
- api 认证:验证 api 密钥或令牌
- 多因素认证:结合多种认证方式
- 第三方登录:如 oauth2、openid connect 等
- 自定义认证:实现特定业务需求的认证逻辑
实战示例(spring boot 3.4.3)
下面我们将通过一个完整示例展示如何在 spring boot 3.4.3 中配置和使用 authenticationmanager。
1. 添加依赖
首先在 pom.xml 中添加必要依赖:
<dependencies>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- 其他依赖 -->
</dependencies>2. 配置 securityconfig
创建 security 配置类,配置 authenticationmanager 和安全规则:
package com.example.demo.config;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.security.authentication.authenticationmanager;
import org.springframework.security.authentication.dao.daoauthenticationprovider;
import org.springframework.security.config.annotation.authentication.configuration.authenticationconfiguration;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.crypto.password.passwordencoder;
import org.springframework.security.web.securityfilterchain;
@configuration
@enablewebsecurity
public class securityconfig {
private final userdetailsservice userdetailsservice;
public securityconfig(userdetailsservice userdetailsservice) {
this.userdetailsservice = userdetailsservice;
}
// 配置 authenticationprovider
@bean
public daoauthenticationprovider authenticationprovider() {
daoauthenticationprovider authprovider = new daoauthenticationprovider();
authprovider.setuserdetailsservice(userdetailsservice);
authprovider.setpasswordencoder(passwordencoder());
return authprovider;
}
// 配置 passwordencoder
@bean
public passwordencoder passwordencoder() {
return new bcryptpasswordencoder();
}
// 配置 authenticationmanager
@bean
public authenticationmanager authenticationmanager(authenticationconfiguration authconfig) throws exception {
return authconfig.getauthenticationmanager();
}
// 配置安全过滤链
@bean
public securityfilterchain filterchain(httpsecurity http) throws exception {
http.csrf(csrf -> csrf.disable())
.authorizehttprequests(auth -> auth
.requestmatchers("/api/public/**").permitall()
.requestmatchers("/api/admin/**").hasrole("admin")
.anyrequest().authenticated()
)
.formlogin(form -> form
.defaultsuccessurl("/api/home", true)
.permitall()
)
.logout(logout -> logout.permitall());
// 注册自定义的 authenticationprovider
http.authenticationprovider(authenticationprovider());
return http.build();
}
}
3. 实现 userdetailsservice
创建自定义的 userdetailsservice 实现,用于加载用户信息:
package com.example.demo.service;
import org.springframework.security.core.userdetails.user;
import org.springframework.security.core.userdetails.userdetails;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.core.userdetails.usernamenotfoundexception;
import org.springframework.stereotype.service;
import java.util.arraylist;
@service
public class customuserdetailsservice implements userdetailsservice {
@override
public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
// 在实际应用中,这里应该从数据库或其他数据源加载用户信息
if ("user".equals(username)) {
return user.withusername("user")
.password("$2a$10$grldnijsqmuvl/au9ofl.edwmoohzzs7.rmnsjz.0fxo/btk76klw") // 密码是 "password"
.roles("user")
.build();
} else if ("admin".equals(username)) {
return user.withusername("admin")
.password("$2a$10$grldnijsqmuvl/au9ofl.edwmoohzzs7.rmnsjz.0fxo/btk76klw") // 密码是 "password"
.roles("admin", "user")
.build();
} else {
throw new usernamenotfoundexception("user not found with username: " + username);
}
}
}
4. 创建认证控制器
创建一个控制器来演示如何在代码中使用 authenticationmanager:
package com.example.demo.controller;
import org.springframework.http.responseentity;
import org.springframework.security.authentication.authenticationmanager;
import org.springframework.security.authentication.usernamepasswordauthenticationtoken;
import org.springframework.security.core.authentication;
import org.springframework.security.core.context.securitycontextholder;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
@requestmapping("/api/auth")
public class authcontroller {
private final authenticationmanager authenticationmanager;
public authcontroller(authenticationmanager authenticationmanager) {
this.authenticationmanager = authenticationmanager;
}
@postmapping("/login")
public responseentity<?> authenticateuser(@requestbody loginrequest loginrequest) {
// 创建 authentication 对象
authentication authentication = authenticationmanager.authenticate(
new usernamepasswordauthenticationtoken(
loginrequest.getusername(),
loginrequest.getpassword()
)
);
// 将认证结果存入 securitycontext
securitycontextholder.getcontext().setauthentication(authentication);
// 返回认证成功的响应
return responseentity.ok(new jwtresponse("dummy-token",
authentication.getname(),
authentication.getauthorities().tostring()));
}
// 内部类用于接收登录请求
public static class loginrequest {
private string username;
private string password;
// getters 和 setters
public string getusername() { return username; }
public void setusername(string username) { this.username = username; }
public string getpassword() { return password; }
public void setpassword(string password) { this.password = password; }
}
// 内部类用于返回认证响应
public static class jwtresponse {
private string token;
private string username;
private string roles;
public jwtresponse(string token, string username, string roles) {
this.token = token;
this.username = username;
this.roles = roles;
}
// getters
public string gettoken() { return token; }
public string getusername() { return username; }
public string getroles() { return roles; }
}
}
5. 测试接口
创建一个简单的测试接口来验证认证效果:
package com.example.demo.controller;
import org.springframework.security.core.authentication;
import org.springframework.security.core.context.securitycontextholder;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class testcontroller {
@getmapping("/api/public/hello")
public string publichello() {
return "hello, public!";
}
@getmapping("/api/home")
public string home() {
authentication auth = securitycontextholder.getcontext().getauthentication();
return "hello, " + auth.getname() + "! you have roles: " + auth.getauthorities();
}
@getmapping("/api/admin/hello")
public string adminhello() {
return "hello, admin!";
}
}
自定义 authenticationmanager
在某些场景下,我们可能需要自定义 authenticationmanager 来实现特定的认证逻辑。例如,实现一个多因素认证:
package com.example.demo.config;
import org.springframework.security.authentication.authenticationmanager;
import org.springframework.security.authentication.authenticationprovider;
import org.springframework.security.authentication.badcredentialsexception;
import org.springframework.security.core.authentication;
import org.springframework.security.core.authenticationexception;
import org.springframework.stereotype.component;
import java.util.list;
@component
public class customauthenticationmanager implements authenticationmanager {
private final list<authenticationprovider> providers;
public customauthenticationmanager(list<authenticationprovider> providers) {
this.providers = providers;
}
@override
public authentication authenticate(authentication authentication) throws authenticationexception {
authenticationexception lastexception = null;
for (authenticationprovider provider : providers) {
if (provider.supports(authentication.getclass())) {
try {
// 调用 authenticationprovider 进行认证
authentication result = provider.authenticate(authentication);
if (result.isauthenticated()) {
// 可以在这里添加额外的认证逻辑,如多因素认证
return result;
}
} catch (authenticationexception e) {
lastexception = e;
}
}
}
if (lastexception != null) {
throw lastexception;
}
throw new badcredentialsexception("authentication failed");
}
}
总结
authenticationmanager 是 spring security 认证体系的核心组件,负责协调认证过程并委托具体的认证逻辑给 authenticationprovider 实现。通过本文的讲解和示例,我们了解了:
authenticationmanager的基本概念和工作原理- 核心实现类及其各自的职责
- 在 spring boot 3.4.3 中如何配置和使用
authenticationmanager - 如何通过自定义实现来满足特定的认证需求
掌握 authenticationmanager 的使用,将有助于我们更好地理解和扩展 spring security 的认证功能,为应用程序提供更安全、更灵活的身份验证机制。
到此这篇关于spring security authenticationmanager 接口详解与实战的文章就介绍到这了,更多相关springsecurity authenticationmanager接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论