自定义 UserDetailsService 实现
创建自定义 `UserDetailsService`,从应用的数据存储中加载特定用户数据以进行身份验证。
自定义 UserDetailsService 实现 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Security 6 & JWT Authentication 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Beyond In-Memory Users
In previous lessons, you might have used in-memory users for simple authentication. This means usernames and passwords are hardcoded directly in your application's configuration.
While easy for testing, real-world applications need to load user data from a persistent source like a database, LDAP, or another service. This is where a custom UserDetailsService comes in!
The UserDetailsService Interface
Spring Security uses the UserDetailsService interface to retrieve user-specific data during authentication. It has just one method you need to implement:
UserDetails loadUserByUsername(String username)
This method is crucial. When a user tries to log in, Spring Security calls this method, passing the username provided by the user.
What is UserDetails?
The loadUserByUsername method must return a UserDetails object. This interface represents the authenticated user's information, including:
- Username
- Password
- Authorities (roles/permissions)
- Account status (e.g., enabled, locked, expired)
Spring Security provides a default implementation called org.springframework.security.core.userdetails.User that you'll often use.
Creating Your Custom Service
To create a custom user service, you simply create a class that implements UserDetailsService. Inside, you'll override the loadUserByUsername method.
This method is where you'll write the logic to fetch user data from your chosen data store. For now, we'll use some hardcoded examples.
Implementing loadUserByUsername
Inside loadUserByUsername, you'll perform these steps:
- Receive the
username. - Look up the user in your data source.
- If found, create a
UserDetailsobject with their details (username, password, roles). - If not found, throw a
UsernameNotFoundException.
Remember, password encoding is vital for security, but we'll cover that in a later lesson. For now, we'll use a plain text password prefix: {noop}.
Code: Basic UserDetailsService
Let's see a simple implementation. This example hardcodes users, simulating fetching from a data source. Run it to see how it works!
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 java.util.Arrays;
import java.util.Collections;
class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// In a real app, you'd fetch user from a database
if ("user".equals(username)) {
return User.withUsername("user")
.password("{noop}password") // {noop} for plain text
.roles("USER")
.build();
}
if ("admin".equals(username)) {
return User.withUsername("admin")
.password("{noop}adminpass")
.roles("ADMIN", "USER")
.build();
}
throw new UsernameNotFoundException("User not found: " + username);
}
}
public class Main {
public static void main(String[] args) {
MyUserDetailsService service = new MyUserDetailsService();
System.out.println("Attempting to load 'user'...");
try {
UserDetails user = service.loadUserByUsername("user");
System.out.println("Loaded User: " + user.getUsername());
System.out.println("Authorities: " + user.getAuthorities());
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("\nAttempting to load 'admin'...");
try {
UserDetails admin = service.loadUserByUsername("admin");
System.out.println("Loaded Admin: " + admin.getUsername());
System.out.println("Authorities: " + admin.getAuthorities());
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("\nAttempting to load 'unknown'...");
try {
service.loadUserByUsername("unknown");
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
}
}Adding Roles and Authorities
Notice in the example, we used .roles("USER") and .roles("ADMIN", "USER").
- Roles are high-level permissions, like 'ADMIN' or 'USER'.
- These roles are converted into GrantedAuthority objects by Spring Security.
- When building the
UserDetailsobject, you specify the roles/authorities the user possesses.
These authorities are later used by Spring Security for authorization (determining what a user can access).
Registering Your Service
Once you've created your custom UserDetailsService, Spring Security needs to know about it. In a Spring Boot application, you typically register it as a Spring bean.
By simply defining your custom service as a @Bean, Spring Security's auto-configuration will usually pick it up and use it for authentication.
The Custom Authentication Flow
Here's how custom authentication typically works with your service:
- User submits login credentials (username, password).
- Spring Security receives the request.
- It calls your custom
UserDetailsService'sloadUserByUsername()method with the provided username. - Your method fetches user data and returns a
UserDetailsobject. - Spring Security then compares the provided password with the password from
UserDetails(after encoding/decoding). - If they match, authentication succeeds!
Check Your Understanding
Consider the core purpose and components of implementing a custom UserDetailsService.
Recap: Custom UserDetailsService
You've learned how to implement a custom UserDetailsService, a fundamental component for advanced user authentication in Spring Security:
- It allows loading user data from any source.
- You implement the
loadUserByUsernamemethod. - This method returns a
UserDetailsobject, containing user credentials and authorities. - It's essential for moving beyond in-memory user management.
Next, we'll dive into securing those passwords with proper encoding!
常见问题解答
「自定义 UserDetailsService 实现」课时是免费的吗?
是的 — 「自定义 UserDetailsService 实现」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。
「自定义 UserDetailsService 实现」这节课中我会学到什么?
创建自定义 `UserDetailsService`,从应用的数据存储中加载特定用户数据以进行身份验证。 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Security 6 & JWT Authentication 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Security 6 & JWT Authentication 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「自定义 UserDetailsService 实现」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Security 6 & JWT Authentication 课中编写并运行代码吗?
能。每节 Spring Security 6 & JWT Authentication 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 自定义 UserDetailsService 实现
- 了解密码编码器
- 集成数据库用户管理
- 使用 Granted Authorities 实现基于角色的授权