Spring Security 超详细使用教程(接入 Spring Boot、前后端分离)

Spring Security 是一个强大且可高度定制的身份验证和访问控制框架,特别适合 Java 应用程序。本文将介绍如何在 Spring Boot 中接入 Spring Security,并与前后端分离模式结合使用。

一、环境准备

  1. 创建 Spring Boot 项目 使用 Spring Initializr 创建一个新的 Spring Boot 项目,选择以下依赖:
  2. Spring Web
  3. Spring Security
  4. Spring Data JPA
  5. H2 Database(或 MySQL)

  6. 项目结构 假设你的项目结构如下: src ├─ main │ ├─ java │ │ └─ com.example.demo │ │ ├─ DemoApplication.java │ │ ├─ config │ │ │ └─ SecurityConfig.java │ │ ├─ controller │ │ │ └─ UserController.java │ │ ├─ model │ │ │ └─ User.java │ │ └─ repository │ │ └─ UserRepository.java │ └─ resources │ └─ application.properties

二、配置应用程序属性

application.properties 中添加以下配置:

# 数据库配置
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

三、创建用户实体类

首先,我们需要定义一个用户模型:

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    // getters and setters
}

四、创建用户仓库

然后,我们需要创建一个用户仓库接口,用于与数据库交互:

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

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

五、配置 Spring Security

接下来,我们需要配置 Spring Security,以便使用用户名和密码进行身份验证:

package com.example.demo.config;

import com.example.demo.repository.UserRepository;
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 UserRepository userRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(username -> {
            User user = userRepository.findByUsername(username);
            if (user != null) {
                return org.springframework.security.core.userdetails.User
                        .withUsername(user.getUsername())
                        .password(user.getPassword())
                        .roles("USER")
                        .build();
            }
            throw new UsernameNotFoundException("User not found");
        }).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/auth/**").permitAll() // 允许访问的路径
            .anyRequest().authenticated() // 其他请求需要认证
            .and()
            .formLogin().permitAll();
    }

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

六、创建用户控制器

接下来,在控制器中处理注册和登录请求:

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public String register(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword())); // 加密密码
        userRepository.save(user);
        return "用户注册成功!";
    }

    @PostMapping("/login")
    public String login() {
        return "登录成功!";
    }
}

七、前端接入

在前后端分离的模式下,前端可以通过 AJAX 调用以上接口进行注册和登录。例如,在 Vue.js 中可以这样调用:

// 注册请求
axios.post('/api/auth/register', {
    username: this.username,
    password: this.password
}).then(response => {
    console.log(response.data);
});

// 登录请求
axios.post('/api/auth/login', {
    username: this.username,
    password: this.password
}).then(response => {
    console.log(response.data);
});

通过以上步骤,你就成功接入了 Spring Security 并且实现了前后端分离的基本认证功能。Spring Security 提供了灵活且强大的安全机制,能够根据需求进行高度定制。希望本教程能帮助到你!

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部