当前位置: 代码网 > it编程>编程语言>Java > Spring Security中的 @PreAuthorize 注解使用方法和示例代码

Spring Security中的 @PreAuthorize 注解使用方法和示例代码

2026年01月23日 Java 我要评论
概述在 spring security 框架中,@preauthorize注解是实现方法级权限控制的重要工具。它提供了灵活而强大的方式来保护应用程序中的方法,确保只有具备特定权限的用户才能访问。本文将

概述

在 spring security 框架中,@preauthorize注解是实现方法级权限控制的重要工具。它提供了灵活而强大的方式来保护应用程序中的方法,确保只有具备特定权限的用户才能访问。本文将详细介绍@preauthorize注解的使用方法、应用场景和示例代码。

什么是 @preauthorize 注解

@preauthorize是 spring security 提供的一个方法级安全注解,用于在方法执行前进行权限检查。它可以基于表达式来定义访问规则,只有当表达式计算结果为true时,方法才会被执行;否则将拒绝访问并抛出accessdeniedexception

与传统的 url 级别的安全控制相比,@preauthorize提供了更细粒度的权限控制,能够直接作用于服务层或控制器层的方法。

启用 @preauthorize 注解

要使用@preauthorize注解,首先需要在 spring 配置类中启用全局方法安全:

import org.springframework.context.annotation.configuration;
import org.springframework.security.config.annotation.method.configuration.enableglobalmethodsecurity;
import org.springframework.security.config.annotation.method.configuration.globalmethodsecurityconfiguration;
@configuration
@enableglobalmethodsecurity(prepostenabled = true)
public class methodsecurityconfig extends globalmethodsecurityconfiguration {
    // 配置内容
}

spring boot 3.4.3 中的配置方式

spring boot 3.x 中,@preauthorize的启用方式与之前版本不同,主要变化是使用@enablemethodsecurity替代了旧的@enableglobalmethodsecurity

基础配置

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.security.config.annotation.method.configuration.enablemethodsecurity;
import org.springframework.security.core.userdetails.user;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.crypto.password.passwordencoder;
import org.springframework.security.provisioning.inmemoryuserdetailsmanager;
@configuration
@enablemethodsecurity(prepostenabled = true) // 启用@preauthorize支持
public class securityconfig {
    // 密码编码器
    @bean
    public passwordencoder passwordencoder() {
        return new bcryptpasswordencoder();
    }
    // 配置用户信息(示例使用内存用户)
    @bean
    public userdetailsservice userdetailsservice() {
        return new inmemoryuserdetailsmanager(
            user.withusername("admin")
                .password(passwordencoder().encode("admin123"))
                .roles("admin")
                .build(),
            user.withusername("user")
                .password(passwordencoder().encode("user123"))
                .roles("user")
                .build(),
            user.withusername("editor")
                .password(passwordencoder().encode("editor123"))
                .roles("editor")
                .build()
        );
    }
}

注意:spring security 6.x 默认不再自动添加 "role_" 前缀,hasrole('admin')实际检查的是 "admin" 权限,而非旧版本的 "role_admin"。

常用表达式语法

@preauthorize注解的值是一个 spel 表达式,常用表达式包括:

  • hasrole('admin'):检查用户是否具有指定角色
  • hasanyrole('admin', 'user'):检查用户是否具有任意指定角色
  • hasauthority('document_delete'):检查用户是否具有指定权限
  • hasanyauthority('create', 'update'):检查用户是否具有任意指定权限
  • principal:获取当前用户的主体对象
  • authentication:获取当前用户的认证对象
  • isauthenticated():检查用户是否已认证
  • permitall():允许所有用户访问
  • denyall():拒绝所有用户访问
  • #parameter:引用方法参数(如#id引用方法中的 id 参数)
  • @beanname.method(arguments):调用 spring 管理的 bean 的方法

实际应用场景与示例

1. 基础访问控制

在控制器层使用@preauthorize控制 api 访问权限:

import org.springframework.security.access.prepost.preauthorize;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class apicontroller {
    // 公开接口,所有人可访问
    @getmapping("/public")
    @preauthorize("permitall()")
    public string publicresource() {
        return "this is a public resource";
    }
    // 需认证后访问
    @getmapping("/protected")
    @preauthorize("isauthenticated()")
    public string protectedresource() {
        return "this is a protected resource";
    }
    // 仅管理员可访问
    @getmapping("/admin")
    @preauthorize("hasrole('admin')")
    public string adminresource() {
        return "this is an admin resource";
    }
    // 管理员或编辑可访问
    @getmapping("/editor")
    @preauthorize("hasanyrole('admin', 'editor')")
    public string editorresource() {
        return "this is an editor resource";
    }
}

2. 服务层方法权限控制

在服务层对业务方法进行权限控制:

import org.springframework.security.access.prepost.preauthorize;
import org.springframework.stereotype.service;
@service
public class documentservice {
    // 需要文档创建权限
    @preauthorize("hasauthority('document_create')")
    public string createdocument(string content) {
        // 业务逻辑:创建文档
        return "document created with content: " + content;
    }
    // 需要文档删除权限或管理员角色
    @preauthorize("hasauthority('document_delete') or hasrole('admin')")
    public void deletedocument(long documentid) {
        // 业务逻辑:删除文档
        system.out.println("deleting document with id: " + documentid);
    }
}

3. 基于方法参数的权限验证

确保用户只能操作自己有权限的数据:

import org.springframework.security.access.prepost.preauthorize;
import org.springframework.stereotype.service;
@service
public class userservice {
    // 确保用户只能更新自己的信息
    @preauthorize("#userid == authentication.principal.id")
    public void updateuserprofile(long userid, string newname) {
        // 业务逻辑:更新用户信息
        system.out.println("updating profile for user " + userid + " to " + newname);
    }
    // 管理员可以查看任何用户,普通用户只能查看自己
    @preauthorize("hasrole('admin') or #userid == authentication.principal.id")
    public string getuserdetails(long userid) {
        // 业务逻辑:获取用户详情
        return "details for user " + userid;
    }
}

4. 调用自定义 bean 进行复杂权限判断

对于复杂的权限逻辑,可以封装到专门的安全服务中:

import org.springframework.security.access.prepost.preauthorize;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/projects")
public class projectcontroller {
    // 项目所有者或管理员可以更新项目
    @putmapping("/{projectid}")
    @preauthorize("@projectsecurityservice.isowner(#projectid, authentication.principal) or hasrole('admin')")
    public string updateproject(@pathvariable long projectid, @requestbody string projectdata) {
        return "project " + projectid + " updated successfully";
    }
}

对应的自定义安全服务:

import org.springframework.stereotype.component;
@component("projectsecurityservice")
public class projectsecurityservice {
    /**
     * 检查用户是否是项目的所有者
     * @param projectid 项目id
     * @param principal 当前用户主体
     * @return 是否为所有者
     */
    public boolean isowner(long projectid, object principal) {
        // 在实际应用中,这里会查询数据库验证项目所有权
        // 这里仅作示例:假设用户"user"拥有id小于100的项目
        string username = principal.tostring();
        return "user".equals(username) && projectid < 100;
    }
}

处理权限不足的情况

@preauthorize表达式返回false时,spring security 会抛出accessdeniedexception。可以通过全局异常处理器统一处理:

import org.springframework.http.httpstatus;
import org.springframework.security.access.accessdeniedexception;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsestatus;
import org.springframework.web.bind.annotation.restcontrolleradvice;
@restcontrolleradvice
public class globalexceptionhandler {
    @exceptionhandler(accessdeniedexception.class)
    @responsestatus(httpstatus.forbidden)
    public string handleaccessdenied(accessdeniedexception ex) {
        return "access denied: you don't have permission to perform this action";
    }
}

注意事项

  • 密码安全:示例中使用了 bcrypt 密码编码器,生产环境务必避免使用明文或{noop}无加密方式。
  • 角色与权限区别hasrole()hasauthority()的区别在于,hasrole()会自动将角色名转换为大写,而hasauthority()则严格匹配。
  • 性能考虑:复杂的 spel 表达式可能影响性能,对于高频调用的方法,应优化权限判断逻辑。
  • 测试:使用@preauthorize后,需要为不同角色和权限的用户编写充分的测试用例。
  • 与 url 安全控制的配合@preauthorize通常与 url 级别的安全控制配合使用,形成多层次的安全防护。

总结

在 spring boot 3.4.3 中,@preauthorize注解通过@enablemethodsecurity启用,提供了强大而灵活的方法级权限控制能力。它支持复杂的 spel 表达式,能够实现基于角色、权限、用户属性和业务逻辑的细粒度权限判断。

合理使用@preauthorize可以显著提高应用程序的安全性,确保敏感操作和数据得到适当的保护。在实际开发中,应根据业务需求选择合适的权限控制策略,并遵循最小权限原则,仅为用户分配必要的权限。

到此这篇关于spring security中的 @preauthorize 注解使用方法和示例代码的文章就介绍到这了,更多相关spring security @preauthorize 注解使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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