当前位置: 代码网 > it编程>编程语言>Java > SpringBoot整合Spring Security实现权限控制的全过程

SpringBoot整合Spring Security实现权限控制的全过程

2026年04月12日 Java 我要评论
一、权限控制核心概念在企业级项目中,认证与授权是安全模块的核心:认证:验证用户身份,确认 “你是谁”,如用户名密码登录、短信验证码登录。授权:用户认证通过后,分配可访问的资源

一、权限控制核心概念

在企业级项目中,认证授权是安全模块的核心:

  • 认证:验证用户身份,确认 “你是谁”,如用户名密码登录、短信验证码登录。
  • 授权:用户认证通过后,分配可访问的资源 / 操作权限,确认 “你能做什么”。

主流 java 权限框架:spring security(spring 生态原生,功能强大)、apache shiro(轻量易用),本文基于 spring security 实现权限控制。

二、权限模块数据模型

权限控制依赖 7 张核心数据表,角色表为核心枢纽,用户、权限、菜单均与角色多对多关联:

  1. 用户表t_user:存储用户账号、密码等信息
  2. 角色表t_role:定义角色(如管理员、普通用户)
  3. 权限表t_permission:定义具体操作权限(如新增、删除、查询)
  4. 菜单表t_menu:定义前端可展示菜单
  5. 用户角色关系表t_user_role:用户与角色多对多关联
  6. 角色权限关系表t_role_permission:角色与权限多对多关联
  7. 角色菜单关系表t_role_menu:角色与菜单多对多关联

三、spring security 入门搭建

1. 引入 maven 依赖

<!-- spring security启动器 -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-security</artifactid>
</dependency>
<!-- web依赖 -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>

2. 核心过滤器链

spring boot 启动时自动加载springsecurityfilterchainfilterchainproxy),包含 15 个核心过滤器,关键过滤器作用:

  • usernamepasswordauthenticationfilter:处理用户名密码登录认证
  • filtersecurityinterceptor:权限校验核心过滤器
  • csrffilter:防跨站请求伪造
  • logoutfilter:处理用户退出登录

四、spring security 核心配置

1. 自定义安全配置类

继承websecurityconfigureradapter,实现匿名资源放行、自定义登录页、认证来源、权限规则配置:

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.builders.websecurity;
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;
/**
 * spring security核心配置类
 */
@configuration
@enablewebsecurity
public class websecurityconfig extends websecurityconfigureradapter {
    @autowired
    private userservice userservice;
    /**
     * 配置静态资源匿名放行
     */
    @override
    public void configure(websecurity web) throws exception {
        // 放行登录页、静态资源、验证码接口
        web.ignoring().antmatchers("/login.html", "/pages/**", "/validatecode/send4login.do");
    }
    /**
     * 配置认证来源(关联自定义userservice)
     */
    @override
    protected void configure(authenticationmanagerbuilder auth) throws exception {
        auth.userdetailsservice(userservice).passwordencoder(passwordencoder());
    }
    /**
     * 配置http请求安全(登录、授权、退出)
     */
    @override
    protected void configure(httpsecurity http) throws exception {
        // 自定义表单登录
        http.formlogin()
                .loginpage("/login.html") // 自定义登录页
                .loginprocessingurl("/login") // 登录请求接口
                .usernameparameter("username") // 用户名参数
                .passwordparameter("password") // 密码参数
                .defaultsuccessurl("/index.html"); // 登录成功跳转页
        // 权限配置
        http.authorizerequests()
                .antmatchers("/pages/b.html").hasauthority("add") // 需add权限
                .antmatchers("/pages/c.html").hasrole("admin") // 需admin角色
                .anyrequest().authenticated(); // 其余资源需登录
        // 退出登录配置
        http.logout()
                .logouturl("/logout") // 退出接口
                .logoutsuccessurl("/login.html"); // 退出成功跳转页
        // 关闭csrf防护(前后端分离可关闭)
        http.csrf().disable();
    }
    /**
     * 密码加密器(bcrypt加密)
     */
    @bean
    public passwordencoder passwordencoder() {
        return new bcryptpasswordencoder();
    }
}

五、数据库认证与密码加密

1. 自定义 userdetailsservice

实现userdetailsservice接口,重写loaduserbyusername方法,从数据库查询用户信息:

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.user;
import org.springframework.security.core.userdetails.userdetails;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.core.userdetails.usernamenotfoundexception;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.stereotype.component;
import java.util.arraylist;
import java.util.hashmap;
import java.util.map;

@component
public class userservice implements userdetailsservice {

    // 模拟数据库用户数据
    private static map<string, userinfo> usermap = new hashmap<>();

    @autowired
    private bcryptpasswordencoder passwordencoder;

    // 初始化加密用户数据
    static {
        usermap.put("admin", new userinfo("admin", new bcryptpasswordencoder().encode("admin")));
        usermap.put("user", new userinfo("user", new bcryptpasswordencoder().encode("123456")));
    }

    @override
    public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
        // 从数据库查询用户
        userinfo userinfo = usermap.get(username);
        if (userinfo == null) {
            throw new usernamenotfoundexception("用户名不存在");
        }

        // 封装权限/角色
        arraylist<grantedauthority> authorities = new arraylist<>();
        if ("admin".equals(username)) {
            authorities.add(new simplegrantedauthority("add"));
            authorities.add(new simplegrantedauthority("role_admin"));
        }

        // 返回spring security规范用户对象
        return new user(userinfo.getusername(), userinfo.getpassword(), authorities);
    }
}

// 用户实体类
class userinfo {
    private string username;
    private string password;

    public userinfo(string username, string password) {
        this.username = username;
        this.password = password;
    }

    // getter/setter
}

2. bcrypt 密码加密

  • 加密:passwordencoder.encode("明文密码")
  • 匹配:passwordencoder.matches("明文密码", "加密后密码")
  • 特点:同一密码每次加密结果不同,自带随机盐,安全系数高

六、两种权限控制方式

方式 1:配置类权限控制

httpsecurity中直接配置 url 权限规则:

http.authorizerequests()
        .antmatchers("/pages/b.html").hasauthority("add") // 需add权限
        .antmatchers("/pages/c.html").hasrole("admin") // 需admin角色
        .anyrequest().authenticated();

方式 2:注解式权限控制

1. 开启注解支持

@configuration
@enableglobalmethodsecurity(prepostenabled = true) // 开启权限注解
public class websecurityconfig extends websecurityconfigureradapter {
}

2. 接口添加权限注解

import org.springframework.security.access.prepost.preauthorize;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@requestmapping("/permission")
public class permissioncontroller {

    // 需add权限才可访问
    @requestmapping("/add")
    @preauthorize("hasauthority('add')")
    public string add() {
        return "新增权限验证通过";
    }

    // 需admin角色才可访问
    @requestmapping("/delete")
    @preauthorize("hasrole('admin')")
    public string delete() {
        return "删除权限验证通过";
    }
}

七、用户退出登录

配置退出接口,请求/logout即可自动清除认证信息,跳转至登录页:

http.logout()
        .logouturl("/logout") // 退出请求路径
        .logoutsuccessurl("/login.html"); // 退出成功跳转页

八、总结

  1. spring security 通过过滤器链实现认证与授权,配置灵活、功能全面。
  2. 核心配置:匿名资源放行、自定义登录页、数据库认证、bcrypt 加密
  3. 权限控制支持配置类注解两种方式,适配不同业务场景。
  4. 生产环境务必使用密码加密、开启csrf 防护、精细化权限配置。

以上就是springboot整合spring security实现权限控制的全过程的详细内容,更多关于springboot spring security权限控制的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com