Spring Security 6 & JWT Authentication · 课时

了解密码编码器

了解 Spring Security 提供的不同密码编码器,以及它们对安全存储密码的重要性。

第 2 / 4 课11 个步骤

了解密码编码器 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Security 6 & JWT Authentication 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Encode Passwords?

Imagine storing your password in a simple text file. Anyone who gains access to that file can immediately see and use your password.

This is a major security risk! In web applications, we never store user passwords in plain, readable text.

Hashing vs. Encryption

When we talk about securing passwords, we use a technique called hashing, not encryption. What's the difference?

  • Encryption: Reversible process. You can encrypt data and later decrypt it back to its original form using a key.
  • Hashing: One-way process. You transform data into a fixed-size string (a hash) that is extremely difficult to reverse. There's no 'decrypting' a hash.

Hashing ensures that even if a database is breached, attackers only get hashes, not actual passwords.

Spring Security's Role

Spring Security provides powerful tools to handle password encoding correctly and securely. It uses a special component called a Password Encoder.

This encoder takes a plain-text password and converts it into a secure hash before storing it. When a user tries to log in, Spring Security encodes their entered password and compares the new hash with the stored hash.

The PasswordEncoder Interface

At the core of Spring Security's password handling is the PasswordEncoder interface. Any class that implements this interface can be used to encode and verify passwords.

It defines two main methods:

  • encode(CharSequence rawPassword): Creates a hash of the raw password.
  • matches(CharSequence rawPassword, String encodedPassword): Checks if a raw password matches an encoded password.

Introducing BCryptPasswordEncoder

One of the most widely recommended and secure password encoders in Spring Security is BCryptPasswordEncoder.

Why is BCrypt so good?

  • Salting: It automatically adds a random 'salt' to each password before hashing, making identical passwords produce different hashes.
  • Adaptive Hashing: It's designed to be computationally intensive, which slows down brute-force attacks. You can even configure its 'strength'.

Encoding a Password with BCrypt

Let's see BCryptPasswordEncoder in action. We'll create an instance and use its encode() method.

Notice how the output is different each time, even for the same input, thanks to salting!

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PasswordEncoderDemo {
  public static void main(String[] args) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String rawPassword = "mysecretpassword";

    String encodedPassword1 = encoder.encode(rawPassword);
    String encodedPassword2 = encoder.encode(rawPassword);

    System.out.println("Encoded 1: " + encodedPassword1);
    System.out.println("Encoded 2: " + encodedPassword2);
  }
}

Verifying a Password with BCrypt

When a user attempts to log in, you don't re-encode their password and compare the strings directly. Instead, you use the matches() method.

This method takes the raw password entered by the user and the stored encoded password, then performs the necessary checks securely.

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PasswordVerifierDemo {
  public static void main(String[] args) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String rawPassword = "userpass";
    String storedEncodedPassword = encoder.encode(rawPassword);

    System.out.println("Stored Encoded: " + storedEncodedPassword);

    // Simulate login attempt with correct password
    boolean matchesCorrect = encoder.matches("userpass", storedEncodedPassword);
    System.out.println("Matches 'userpass': " + matchesCorrect);

    // Simulate login attempt with incorrect password
    boolean matchesIncorrect = encoder.matches("wrongpass", storedEncodedPassword);
    System.out.println("Matches 'wrongpass': " + matchesIncorrect);
  }
}

Other Secure Encoders

While BCrypt is very common, Spring Security also supports other strong password hashing algorithms. These include:

  • Pbkdf2PasswordEncoder: Uses PBKDF2 (Password-Based Key Derivation Function 2).
  • SCryptPasswordEncoder: Based on scrypt, designed to be resistant to GPU-based attacks.
  • Argon2PasswordEncoder: Uses Argon2, winner of the Password Hashing Competition.

These all serve the same purpose: securely hashing passwords to prevent easy cracking.

DelegatingPasswordEncoder

Spring Security 5.0 introduced DelegatingPasswordEncoder as the default. This is a very important concept!

It allows you to:

  • Support multiple encoding formats simultaneously (e.g., if you're migrating from an older algorithm).
  • Define a default encoder while still being able to verify passwords encoded with other algorithms.

It prefixes the encoded password with an identifier (e.g., {bcrypt}) to indicate which algorithm was used.

Quick Check: Password Security

You've learned about the importance of password encoding. Let's test your understanding!

Recap: Secure Password Storage

In this lesson, we explored the critical role of password encoders in Spring Security:

  • Passwords must always be hashed, not encrypted, for secure storage.
  • The PasswordEncoder interface defines how passwords are encoded and verified.
  • BCryptPasswordEncoder is a strong, recommended encoder that uses salting and adaptive hashing.
  • DelegatingPasswordEncoder allows for flexible support of multiple hashing algorithms.

Proper password encoding is fundamental to protecting user accounts in any application.

免费开始

用 AI 导师学习 Java — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「了解密码编码器」课时是免费的吗?

是的 — 「了解密码编码器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

「了解密码编码器」这节课中我会学到什么?

了解 Spring Security 提供的不同密码编码器,以及它们对安全存储密码的重要性。 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Security 6 & JWT Authentication 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Security 6 & JWT Authentication 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「了解密码编码器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Security 6 & JWT Authentication 课中编写并运行代码吗?

能。每节 Spring Security 6 & JWT Authentication 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 自定义 UserDetailsService 实现
  2. 了解密码编码器
  3. 集成数据库用户管理
  4. 使用 Granted Authorities 实现基于角色的授权
← 返回 Spring Security 6 & JWT Authentication