Rumah >Java >javaTutorial >Sistem log masuk dengan token JWT dan kata laluan tetapan semula e-mel
Aplikasi Log Masuk Musim Bunga ialah sistem pengurusan pengguna yang selamat dan teguh dibina menggunakan Spring Boot. Projek ini menunjukkan pendekatan moden untuk melaksanakan fungsi pengesahan, kebenaran dan akaun pengguna. Ciri utama termasuk pendaftaran pengguna, pengendalian kata laluan selamat dengan BCrypt, tetapan semula kata laluan berasaskan e-mel dan pengesahan JWT (JSON Web Token). Direka bentuk dengan mengambil kira kebolehlanjutan dan skalabiliti, aplikasi ini berfungsi sebagai asas yang sangat baik untuk projek yang memerlukan pengurusan pengguna dan kawalan akses berasaskan peranan.
Dengan memanfaatkan alatan berkuasa Spring seperti Spring Security, Spring Data JPA dan JavaMailSender, projek ini memastikan amalan terbaik dalam keselamatan, kebolehselenggaraan dan kemudahan integrasi. Sama ada anda sedang membina aplikasi web yang kecil atau sistem perusahaan yang besar, projek ini menyediakan titik permulaan yang praktikal dan tersusun dengan baik untuk mengurus akaun pengguna dengan selamat.
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Untuk menjalankan pangkalan data PostgreSQL, buat fail docker-compose.yaml:
services: postgres: image: postgres:latest ports: - "5432:5432" environment: - POSTGRES_DB=database - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data:
Lari:
docker compose up -d
spring.application.name=login_app spring.datasource.url=jdbc:postgresql://localhost:5432/database spring.datasource.username=admin spring.datasource.password=admin spring.mail.host=sandbox.smtp.mailtrap.io spring.mail.port=2525 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.config.import=classpath:env.properties jwt.public.key=classpath:public.key jwt.private.key=classpath:private.key
spring.mail.username=<Get in your mailtrap account> spring.mail.password=<Get in your mailtrap account>
Lihat dalam siaran ini cara menjana kunci asimetri
login_app/ ├── .mvn/ # Maven folder (Maven configurations) ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── mspilari/ │ │ │ └── login_app/ │ │ │ ├── configs/ # Security, authentication, and other configurations │ │ │ ├── domains/ # Main application domains │ │ │ │ ├── email/ # Email-related logic │ │ │ │ └── user/ # User-related logic │ │ │ ├── exceptions/ # Custom exceptions and error handling │ │ │ └── utils/ # Utilities and helpers │ │ └── resources/ # Resources (e.g., configuration files) │ └── test/ # Application tests ├── target/ # Build folder generated by Maven ├── .gitattributes # Git attributes configuration ├── .gitignore # Git ignore file ├── docker-compose.yaml # Docker Compose configuration ├── HELP.md # Project help documentation ├── mvnw # Maven Wrapper script for Linux ├── mvnw.cmd # Maven Wrapper script for Windows └── pom.xml # Maven configuration file
BCryptPasswordConfig.java
package dev.mspilari.login_app.configs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class BCryptPasswordConfig { @Bean public BCryptPasswordEncoder bPasswordEncoder() { return new BCryptPasswordEncoder(); } }
@Konfigurasi
@Kacang
BCryptPasswordEncoder
Kaedah bPasswordEncoder()
JwtConfig.java
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
services: postgres: image: postgres:latest ports: - "5432:5432" environment: - POSTGRES_DB=database - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data:
docker compose up -d
spring.application.name=login_app spring.datasource.url=jdbc:postgresql://localhost:5432/database spring.datasource.username=admin spring.datasource.password=admin spring.mail.host=sandbox.smtp.mailtrap.io spring.mail.port=2525 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.config.import=classpath:env.properties jwt.public.key=classpath:public.key jwt.private.key=classpath:private.key
spring.mail.username=<Get in your mailtrap account> spring.mail.password=<Get in your mailtrap account>
login_app/ ├── .mvn/ # Maven folder (Maven configurations) ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── mspilari/ │ │ │ └── login_app/ │ │ │ ├── configs/ # Security, authentication, and other configurations │ │ │ ├── domains/ # Main application domains │ │ │ │ ├── email/ # Email-related logic │ │ │ │ └── user/ # User-related logic │ │ │ ├── exceptions/ # Custom exceptions and error handling │ │ │ └── utils/ # Utilities and helpers │ │ └── resources/ # Resources (e.g., configuration files) │ └── test/ # Application tests ├── target/ # Build folder generated by Maven ├── .gitattributes # Git attributes configuration ├── .gitignore # Git ignore file ├── docker-compose.yaml # Docker Compose configuration ├── HELP.md # Project help documentation ├── mvnw # Maven Wrapper script for Linux ├── mvnw.cmd # Maven Wrapper script for Windows └── pom.xml # Maven configuration file
Pengekodan JWT (Penjanaan Token):
package dev.mspilari.login_app.configs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class BCryptPasswordConfig { @Bean public BCryptPasswordEncoder bPasswordEncoder() { return new BCryptPasswordEncoder(); } }
Penyahkodan JWT (Pengesahan Token):
package dev.mspilari.login_app.configs; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; @Configuration public class JwtConfig { @Value("${jwt.public.key}") private RSAPublicKey publicKey; @Value("${jwt.private.key}") private RSAPrivateKey privateKey; @Bean public JwtEncoder jwtEncoder() { var jwk = new RSAKey.Builder(this.publicKey).privateKey(this.privateKey).build(); var jwks = new ImmutableJWKSet<>(new JWKSet(jwk)); return new NimbusJwtEncoder(jwks); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.publicKey).build(); } }
SecurityConfig.java
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
services: postgres: image: postgres:latest ports: - "5432:5432" environment: - POSTGRES_DB=database - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data:
docker compose up -d
spring.application.name=login_app spring.datasource.url=jdbc:postgresql://localhost:5432/database spring.datasource.username=admin spring.datasource.password=admin spring.mail.host=sandbox.smtp.mailtrap.io spring.mail.port=2525 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.config.import=classpath:env.properties jwt.public.key=classpath:public.key jwt.private.key=classpath:private.key
spring.mail.username=<Get in your mailtrap account> spring.mail.password=<Get in your mailtrap account>
login_app/ ├── .mvn/ # Maven folder (Maven configurations) ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── mspilari/ │ │ │ └── login_app/ │ │ │ ├── configs/ # Security, authentication, and other configurations │ │ │ ├── domains/ # Main application domains │ │ │ │ ├── email/ # Email-related logic │ │ │ │ └── user/ # User-related logic │ │ │ ├── exceptions/ # Custom exceptions and error handling │ │ │ └── utils/ # Utilities and helpers │ │ └── resources/ # Resources (e.g., configuration files) │ └── test/ # Application tests ├── target/ # Build folder generated by Maven ├── .gitattributes # Git attributes configuration ├── .gitignore # Git ignore file ├── docker-compose.yaml # Docker Compose configuration ├── HELP.md # Project help documentation ├── mvnw # Maven Wrapper script for Linux ├── mvnw.cmd # Maven Wrapper script for Windows └── pom.xml # Maven configuration file
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
services: postgres: image: postgres:latest ports: - "5432:5432" environment: - POSTGRES_DB=database - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data:
UserDto.java
docker compose up -d
UserRedeemPasswordDto.java
spring.application.name=login_app spring.datasource.url=jdbc:postgresql://localhost:5432/database spring.datasource.username=admin spring.datasource.password=admin spring.mail.host=sandbox.smtp.mailtrap.io spring.mail.port=2525 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.config.import=classpath:env.properties jwt.public.key=classpath:public.key jwt.private.key=classpath:private.key
UserResetPasswordDto.java
spring.mail.username=<Get in your mailtrap account> spring.mail.password=<Get in your mailtrap account>
UserEntity.java
login_app/ ├── .mvn/ # Maven folder (Maven configurations) ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── mspilari/ │ │ │ └── login_app/ │ │ │ ├── configs/ # Security, authentication, and other configurations │ │ │ ├── domains/ # Main application domains │ │ │ │ ├── email/ # Email-related logic │ │ │ │ └── user/ # User-related logic │ │ │ ├── exceptions/ # Custom exceptions and error handling │ │ │ └── utils/ # Utilities and helpers │ │ └── resources/ # Resources (e.g., configuration files) │ └── test/ # Application tests ├── target/ # Build folder generated by Maven ├── .gitattributes # Git attributes configuration ├── .gitignore # Git ignore file ├── docker-compose.yaml # Docker Compose configuration ├── HELP.md # Project help documentation ├── mvnw # Maven Wrapper script for Linux ├── mvnw.cmd # Maven Wrapper script for Windows └── pom.xml # Maven configuration file
Role.java
package dev.mspilari.login_app.configs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class BCryptPasswordConfig { @Bean public BCryptPasswordEncoder bPasswordEncoder() { return new BCryptPasswordEncoder(); } }
UserRepository.java
package dev.mspilari.login_app.configs; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; @Configuration public class JwtConfig { @Value("${jwt.public.key}") private RSAPublicKey publicKey; @Value("${jwt.private.key}") private RSAPrivateKey privateKey; @Bean public JwtEncoder jwtEncoder() { var jwk = new RSAKey.Builder(this.publicKey).privateKey(this.privateKey).build(); var jwks = new ImmutableJWKSet<>(new JWKSet(jwk)); return new NimbusJwtEncoder(jwks); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.publicKey).build(); } }
UserService.java
@Configuration
GlobalException.java
@Value("${jwt.public.key}") private RSAPublicKey publicKey; @Value("${jwt.private.key}") private RSAPrivateKey privateKey;
JwtActions.java
jwt.public.key=<your-public-key> jwt.private.key=<your-private-key>
Dalam projek ini, kami berjaya melaksanakan sistem pengesahan pengguna yang selamat dan kaya dengan ciri menggunakan Spring Boot. Di luar fungsi teras seperti pendaftaran pengguna, log masuk, dan pengesahan berasaskan JWT, aplikasi itu juga menggabungkan sistem pemulihan kata laluan. Pengguna boleh menetapkan semula kata laluan mereka melalui pautan e-mel, memastikan proses pemulihan yang lancar dan selamat.
Untuk memudahkan pemulihan kata laluan berasaskan e-mel, kami menyepadukan E-mel Musim Bunga dengan Mailtrap, perkhidmatan ujian e-mel yang selamat dan cekap. Ini membolehkan aplikasi menghantar pautan tetapan semula kata laluan dengan token sementara sambil memastikan bahawa e-mel dihantar dengan selamat dan diuji dalam persekitaran terkawal. Persediaan ini menunjukkan cara mengendalikan aliran kerja sensitif seperti pemulihan kata laluan tanpa mendedahkan pengguna sebenar kepada isu yang berpotensi semasa pembangunan dan ujian.
Gabungan amalan pengesahan selamat, pengurusan kata laluan yang mantap dan penyepaduan e-mel yang lancar menjadikan aplikasi ini asas yang boleh dipercayai untuk mana-mana sistem web moden. Pembangun boleh menyesuaikan amalan ini untuk memenuhi keperluan khusus mereka, memastikan kebolehskalaan dan kepercayaan pengguna. Dengan memanfaatkan amalan dan alatan terbaik seperti Spring Security dan Mailtrap, kami telah menunjukkan cara membina aplikasi yang selamat dan memfokuskan pengguna dengan mudah.
Atas ialah kandungan terperinci Sistem log masuk dengan token JWT dan kata laluan tetapan semula e-mel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!