锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. 使用Spring Boot实现用户认证和授权

使用Spring Boot实现用户认证和授权

0
  • 软件开发
  • 发布于 2024-08-16
  • 0 次阅读
黄健
黄健

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

文章目录

    • 引言
    • 第一章 Spring Boot 概述
      • 1.1 什么是 Spring Boot
      • 1.2 Spring Boot 的主要特性
    • 第二章 用户认证和授权基础知识
      • 2.1 用户认证
      • 2.2 用户授权
      • 2.3 Spring Security 概述
    • 第三章 项目初始化
    • 第四章 实现用户认证和授权
      • 4.1 定义用户实体类和角色实体类
      • 4.2 创建 Repository 接口
      • 4.3 实现 Service 类
      • 4.4 配置 Spring Security
      • 4.5 创建 Controller 类
      • 4.6 创建 Thymeleaf 模板
    • 第五章 部署与监控
      • 5.1 部署 Spring Boot 应用
      • 5.2 使用 Docker 部署 Spring Boot 应用
      • 5.3 监控 Spring Boot 应用
    • 结论

引言

在现代 Web 应用中,用户认证和授权是必不可少的功能。它们确保只有经过验证的用户才能访问应用,并根据用户的角色和权限进行相应的操作。Spring Boot 通过集成 Spring Security,提供了强大的安全功能,简化了用户认证和授权的实现。本文将详细探讨如何使用 Spring Boot 实现用户认证和授权,并提供具体的代码示例和应用案例。

第一章 Spring Boot 概述

1.1 什么是 Spring Boot

Spring Boot 是一个基于 Spring 框架的开源项目,旨在通过简化配置和快速开发,帮助开发者构建独立、生产级的 Spring 应用。Spring Boot 通过自动化配置、内嵌服务器和多样化的配置方式,使得开发者能够更加专注于业务逻辑,而不需要花费大量时间在繁琐的配置上。

1.2 Spring Boot 的主要特性

  • 自动化配置:通过自动化配置减少了大量的手动配置工作,开发者只需定义少量的配置,即可启动一个完整的 Spring 应用。
  • 内嵌服务器:提供内嵌的 Tomcat、Jetty 和 Undertow 服务器,方便开发者在开发和测试阶段快速启动和运行应用。
  • 独立运行:应用可以打包成一个可执行的 JAR 文件,包含所有依赖项,可以独立运行,不需要外部的应用服务器。
  • 生产级功能:提供了监控、度量、健康检查等生产级功能,方便开发者管理和监控应用的运行状态。

第二章 用户认证和授权基础知识

2.1 用户认证

用户认证(Authentication)是验证用户身份的过程。常见的认证方式包括用户名和密码、OAuth、JWT 等。认证的目的是确保只有合法用户才能访问系统。

2.2 用户授权

用户授权(Authorization)是对经过认证的用户进行权限控制的过程。授权决定了用户可以访问哪些资源和执行哪些操作。常见的授权方式包括基于角色的访问控制(RBAC)和基于权限的访问控制(PBAC)。

2.3 Spring Security 概述

Spring Security 是 Spring 框架的一个子项目,提供了全面的安全服务支持。Spring Security 通过高度可扩展的安全机制,简化了用户认证和授权的实现。

第三章 项目初始化

使用 Spring Initializr 生成一个 Spring Boot 项目,并添加所需依赖。

<!-- 示例:通过Spring Initializr生成的pom.xml配置文件 -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>auth-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>auth-demo</name>
    <description>Demo project for Spring Boot Authentication and Authorization</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

第四章 实现用户认证和授权

4.1 定义用户实体类和角色实体类

定义用户实体类和角色实体类,并配置 JPA 注解。

// 示例:用户实体类
package com.example.authdemo.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String username;
    private String password;
    private boolean enabled;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    // Getters and Setters
}

// 示例:角色实体类
package com.example.authdemo.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();

    // Getters and Setters
}

4.2 创建 Repository 接口

创建用户和角色的 JPA Repository 接口,用于数据访问操作。

// 示例:用户Repository接口
package com.example.authdemo.repository;

import com.example.authdemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

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

// 示例:角色Repository接口
package com.example.authdemo.repository;

import com.example.authdemo.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
}

4.3 实现 Service 类

创建 UserDetailsService 实现类,处理用户认证逻辑。

// 示例:自定义UserDetailsService实现类
package com.example.authdemo.service;

import com.example.authdemo.model.User;
import com.example.authdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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;

@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 with username: " + username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getRoles());
    }
}

4.4 配置 Spring Security

配置 Spring Security,实现用户认证和授权。

// 示例:Spring Security配置类
package com.example.authdemo.config;

import com.example.authdemo.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 userDetailsService;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/", "/home", "/about").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }

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

4.5 创建 Controller 类

创建控制器类,处理用户登录、注册等请求。

// 示例:用户控制器类
package com.example.authdemo.controller;

import com.example.authdemo.model.User;
import com.example.authdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

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

    @GetMapping("/register")
    public String register(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/login";
    }
}

4.6 创建 Thymeleaf 模板

创建 Thymeleaf 模板,提供用户登录和注册页面。

<!-- 示例:login.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <h1>Login</h1>
    <form th:action="@{/login}" method="post">
        <div>
            <label for="username">Username</label>
            <input type="text" id="username"  required>
        </div>
        <div>
            <label for="password">Password</label>
            <input type="password" id="password"  required>
        </div>
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>
</html>
<!-- 示例:register.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Register</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <h1>Register</h1>
    <form th:action="@{/register}" method="post" th:object="${user}">
        <div>
            <label for="username">Username</label>
            <input type="text" id="username" th:field="*{username}" required>
        </div>
        <div>
            <label for="password">Password</label>
            <input type="password" id="password" th:field="*{password}" required>
        </div>
        <div>
            <button type="submit">Register</button>
        </div>
    </form>
</body>
</html>

第五章 部署与监控

5.1 部署 Spring Boot 应用

Spring Boot 应用可以通过多种方式进行部署,包括打包成 JAR 文件、Docker 容器等。

# 打包Spring Boot应用
mvn clean package

# 运行Spring Boot应用
java -jar target/auth-demo-0.0.1-SNAPSHOT.jar

5.2 使用 Docker 部署 Spring Boot 应用

Docker 是一个开源的容器化平台,可以帮助开发者将 Spring Boot 应用打包成容器镜像,并在任何环境中运行。

# 示例:Dockerfile文件
FROM openjdk:11-jre-slim
VOLUME /tmp
COPY target/auth-demo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
# 构建Docker镜像
docker build -t spring-boot-auth-demo .

# 运行Docker容器
docker run -p 8080:8080 spring-boot-auth-demo

5.3 监控 Spring Boot 应用

Spring Boot Actuator 提供了丰富的监控功能,通过 Prometheus 和 Grafana,可以实现对 Spring Boot 应用的监控和可视化。

<!-- 示例:集成Prometheus的pom.xml配置文件 -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
# 示例:Prometheus配置文件
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    prometheus:
      enabled: true

结论

通过 Spring Boot 和 Spring Security,开发者可以高效地实现用户认证和授权功能,确保系统的安全性和可靠性。本文详细介绍了用户认证和授权的基础知识、Spring Boot 项目的初始化、具体实现以及部署和监控,帮助读者深入理解和掌握 Spring Boot 在用户认证和授权中的应用。希望本文能够为您进一步探索和应用 Spring Boot 提供有价值的参考。

标签: #Spring Boot 173 #软件开发 1171 #JAVA 991
相关文章

万字:支付“核心系统”详解 2024-11-02 15:33

专栏作者:隐墨星辰 \| 主编:陈天宇宙 这篇文章也尝试化繁为简,探寻支付系统的本质,讲清楚在线支付系统最核心的一些概念和设计理念。 虽然支付行业已经过了风头最劲的时光,但跨境支付仍然在蓬勃发展,每年依然有很多新人进入这个行业,这篇文章尝试为这些刚入行的新人提供一点帮助。 文章只介绍一些支付行业十几

资深支付架构师视角:实战从问题定义到代码落地的完整套路 2024-11-02 15:33

前言 今天从一个实际案例入手,介绍站在架构师的角度,如何识别并定义问题,提炼需求,技术方案选型,再到详细设计,最后利用AI的能力协助写出核心的代码,验证与调优。 解决问题存在一定的模式,也可以称之为框架,总结出自己的思考和解题框架,以后再碰到同类型的问题就可以如庖丁解牛一样容易。 很多年前,我写代码

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

设计模式第16讲——迭代器模式(Iterator) 2024-10-08 11:24

一、什么是迭代器模式 迭代器模式是一种行为型设计模式,它提供了一种统一的方式来访问集合对象中的元素,而不是暴露集合内部的表示方式。简单地说,就是将遍历集合的责任封装到一个单独的对象中,我们可以按照特定的方式访问集合中的元素。 二、角色组成 抽象迭代器(Iterator):定义了遍历聚合对象所需的方法

vue2路由和vue3路由区别及原理 2024-10-08 11:24

一、Vue2 与 Vue3 路由的区别 1. 创建路由实例方式的不同 Vue 2 中,通过 Vue.use() 注册路由插件,并通过 new VueRouter() 来创建路由实例。 import Vue from 'vue';import VueRouter from 'vue-router';i

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.