Ask me anything
Ithy Logo
Sign in to save

基于 Spring Boot、Spring Cloud、Nacos、Spring Cloud Security 和 Spring Cloud Alibaba 的简单后台管理系统实现方案

java - why do we always put Hibernate, Spring and Strut in one app ...

概述

本指南详细介绍了如何使用 Spring Boot、Spring Cloud、Nacos、Spring Cloud Security 和 Spring Cloud Alibaba 构建一个简单的后台管理系统。该系统将认证与授权功能独立为一个微服务,确保系统的可扩展性和维护性。通过遵循以下步骤,您可以实现一个高效、模块化的后台管理系统。

项目结构和依赖配置

1. 项目结构

首先,定义项目的总体结构。建议采用微服务架构,将不同功能模块分离,以提高系统的可维护性和扩展性。以下是推荐的项目结构:


project-root/
│
├── parent-pom/              // 父项目,管理所有子项目的依赖和配置
├── auth-service/            // 认证与授权微服务
├── admin-service/           // 后台管理系统微服务
├── gateway-service/         // API 网关服务
└── common-module/           // 公共模块,如工具类、常量等
  

2. 父项目配置

父项目用于统一管理所有子项目的依赖和插件配置,简化子项目的配置工作。以下是一个典型的 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>parent-pom</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>auth-service</module>
        <module>admin-service</module>
        <module>gateway-service</module>
        <module>common-module</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
  

3. 子项目配置

每个子项目(如认证服务、后台管理服务)需要在其 pom.xml 文件中继承父项目,并添加必要的依赖。

3.1 认证与授权服务 (auth-service)

该服务负责用户的认证和授权,使用 Spring Security 和 OAuth2 实现安全机制。


<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">
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-pom</artifactId>
        <version>1.0.0</version>
    </parent>

    <artifactId>auth-service</artifactId>

    <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.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <!-- 其他必要依赖 --</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  

3.2 后台管理服务 (admin-service)

该服务负责处理后台管理相关的业务逻辑,如用户管理、角色管理等。


<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">
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-pom</artifactId>
        <version>1.0.0</version>
    </parent>

    <artifactId>admin-service</artifactId>

    <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.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!-- 其他必要依赖 --</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  

3.3 网关服务 (gateway-service)

网关服务负责请求的路由、负载均衡、安全性等功能,是整个系统的入口。


<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">
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-pom</artifactId>
        <version>1.0.0</version>
    </parent>

    <artifactId>gateway-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- 其他必要依赖 --</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  

配置 Nacos 服务注册与配置中心

1. 下载并启动 Nacos

请参考 Nacos 官方文档 了解如何下载和启动 Nacos 服务。

2. 配置 Nacos 作为服务注册中心

在每个微服务的配置文件(如 application.yml 或 bootstrap.properties)中配置 Nacos 的地址。


spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
      config:
        server-addr: 127.0.0.1:8848
  application:
    name: your-service-name
  

3. 服务注册

确保所有微服务在启动时能够成功注册到 Nacos 中。可以通过访问 Nacos 控制台 来验证服务注册情况。

实现认证与授权微服务

1. 安全配置

配置 Spring Security 以实现基本的安全性,并使用 OAuth2 或 JWT 进行认证和授权。


package com.example.authservice.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.*;
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
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/auth/**", "/register").permitAll()
                .anyRequest().authenticated()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("admin")
            .password(passwordEncoder().encode("password"))
            .roles("ADMIN");
        // 也可以配置数据库用户详情服务
    }

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

2. JWT 工具类

用于生成和解析 JWT 令牌的工具类。


package com.example.authservice.util;

import io.jsonwebtoken.*;
import java.util.Date;

public class JwtTokenUtil {
    private static final String SECRET = "your-secret-key";
    private static final long EXPIRATION = 86400000; // 24小时

    public static String generateToken(String username) {
        return Jwts.builder()
            .setSubject(username)
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
            .signWith(SignatureAlgorithm.HS512, SECRET)
            .compact();
    }

    public static String parseToken(String token) {
        return Jwts.parser()
            .setSigningKey(SECRET)
            .parseClaimsJws(token)
            .getBody()
            .getSubject();
    }
}
  

3. JWT 过滤器

用于处理每个请求,验证 JWT 令牌。


package com.example.authservice.filter;

import com.example.authservice.util.JwtTokenUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    public JwtAuthorizationFilter(AuthenticationManager authManager) {
        super(authManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    javax.servlet.http.HttpServletResponse response, 
                                    FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }

        String token = header.replace("Bearer ", "");
        String username = JwtTokenUtil.parseToken(token);

        if (username != null) {
            UsernamePasswordAuthenticationToken auth = 
                new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        chain.doFilter(request, response);
    }
}
  

4. 认证控制器

提供用户登录和注册的接口。


package com.example.authservice.controller;

import com.example.authservice.util.JwtTokenUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final AuthenticationManager authenticationManager;

    public AuthController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    public void login(@RequestParam String username, 
                      @RequestParam String password, 
                      HttpServletResponse response) throws IOException {
        try {
            authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password));
        } catch (AuthenticationException e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        String token = JwtTokenUtil.generateToken(username);
        response.setHeader("Authorization", "Bearer " + token);
    }
    
    // 添加注册接口
}
  

实现后台管理服务

1. RESTful API 开发

使用 Spring Web 开发后台管理所需的 RESTful API,如用户管理、角色管理等。

2. 数据访问层

选择合适的持久化机制,如 MySQL 进行关系型数据存储,使用 Spring Data JPA 进行数据库交互。


package com.example.adminservice.repository;

import com.example.adminservice.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);
}
  

3. 安全配置

配置 Spring Security 以使用 JWT 进行认证,确保只有经过授权的用户才能访问后台管理 API。


package com.example.adminservice.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .addFilterBefore(new JwtAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
  

配置网关服务

1. 路由配置

配置 API 网关的路由规则,将请求路由到对应的微服务。


spring:
  cloud:
    gateway:
      routes:
        - id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/auth/**

        - id: admin-service
          uri: lb://admin-service
          predicates:
            - Path=/admin/**

        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/user/**
  

2. 安全配置

配置网关的安全策略,确保所有通过网关的请求都经过认证和授权。

部署和测试

1. 启动 Nacos 服务

确保 Nacos 服务已启动,并可通过 Nacos 控制台 进行访问。

2. 启动微服务

  1. 认证与授权服务 (auth-service)
  2. 后台管理服务 (admin-service)
  3. 网关服务 (gateway-service)

3. 测试功能

  1. 用户登录:使用 Postman 或其他 API 测试工具发送登录请求,获取 JWT 令牌。
  2. 访问受保护资源:使用获取的 JWT 令牌访问后台管理 API,验证权限控制。
  3. 服务发现:通过 Nacos 控制台确认所有服务已正确注册。

优化和扩展

1. 引入 API 网关

为提高系统的安全性和可管理性,可以引入 API 网关,如 Spring Cloud Gateway,实现统一的路由控制、负载均衡和安全策略。

2. 实现细粒度的权限控制

基于角色和权限的控制,确保不同用户只能访问其授权的资源。

3. 日志与监控

集成日志系统(如 ELK Stack)和监控系统(如 Prometheus、Grafana),实现对系统运行状况的实时监控和日志分析。

4. 高可用性和容错

通过引入断路器(如 Resilience4j)、服务熔断和重试机制,提高系统的稳定性和容错能力。

参考资料

总结

通过以上步骤,您可以构建一个基于 Spring Boot、Spring Cloud、Nacos、Spring Cloud Security 和 Spring Cloud Alibaba 的简单后台管理系统。将认证与授权功能独立为一个微服务,不仅提升了系统的安全性,还增强了系统的可扩展性和可维护性。根据具体的业务需求,您可以进一步优化和扩展系统功能,确保系统在实际应用中的高效运行。


Last updated January 6, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI