使用Java和Spring Boot实现用户身份验证

使用Java和Spring Boot实现用户身份验证

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

在现代Web应用中,用户身份验证是确保应用安全的核心部分。通过身份验证,我们可以识别用户的身份,并为他们提供相应的访问权限。本文将介绍如何使用Java和Spring Boot实现用户身份验证,包括配置Spring Security、创建用户实体、设置安全过滤器等。

1. 引入Spring Security依赖

在Spring Boot项目中引入Spring Security依赖是第一步。我们需要在pom.xml中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 配置Spring Security

为了配置Spring Security,我们需要创建一个配置类SecurityConfig,并在其中定义身份验证的逻辑。

java 复制代码
package cn.juwatech.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessURL("/home", true)
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

3. 创建用户实体类

我们需要创建一个用户实体类来表示用户信息,并与数据库表进行映射。

java 复制代码
package cn.juwatech.model;

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    // getters and setters
}

4. 创建Repository接口

创建一个Repository接口来访问用户数据。

java 复制代码
package cn.juwatech.repository;

import cn.juwatech.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

5. 自定义UserDetailsService

我们需要实现一个自定义的UserDetailsService来从数据库中加载用户信息。

java 复制代码
package cn.juwatech.service;

import cn.juwatech.model.User;
import cn.juwatech.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.HashSet;
import java.util.Set;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}

6. 修改SecurityConfig以使用自定义UserDetailsService

我们需要在SecurityConfig中配置自定义的UserDetailsService。

java 复制代码
package cn.juwatech.config;

import cn.juwatech.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessURL("/home", true)
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

7. 创建登录页面和控制器

创建一个简单的登录页面和控制器来处理登录请求。

login.html

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form th:action="@{/login}" method="post">
        <div>
            <label>Username:</label>
            <input type="text" name="username"/>
        </div>
        <div>
            <label>Password:</label>
            <input type="password" name="password"/>
        </div>
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>
</html>

LoginController.java

java 复制代码
package cn.juwatech.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}

8. 创建主页控制器

创建一个简单的主页控制器来处理登录成功后的请求。

HomeController.java

java 复制代码
package cn.juwatech.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}

home.html

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome Home!</h1>
    <a th:href="@{/logout}">Logout</a>
</body>
</html>

9. 运行项目

启动Spring Boot应用并访问http://localhost:8080/login,使用用户名user和密码password登录,成功登录后将重定向到主页。

总结

通过本文,我们学习了如何使用Java和Spring Boot实现用户身份验证。从配置Spring Security到创建自定义UserDetailsService,我们逐步实现了一个简单而完整的用户身份验证系统。

微赚淘客系统3.0小编出品,必属精品,转载请注明出处!

相关推荐
顾北川_野4 分钟前
Android 手机设备的OEM-unlock解锁 和 adb push文件
android·java
江深竹静,一苇以航6 分钟前
springboot3项目整合Mybatis-plus启动项目报错:Invalid bean definition with name ‘xxxMapper‘
java·spring boot
远望清一色12 分钟前
基于MATLAB的实现垃圾分类Matlab源码
开发语言·matlab
confiself22 分钟前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
Wlq041527 分钟前
J2EE平台
java·java-ee
XiaoLeisj33 分钟前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee
杜杜的man37 分钟前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang
幼儿园老大*38 分钟前
走进 Go 语言基础语法
开发语言·后端·学习·golang·go
半桶水专家39 分钟前
go语言中package详解
开发语言·golang·xcode
llllinuuu39 分钟前
Go语言结构体、方法与接口
开发语言·后端·golang