Spring Security中的@PreAuthorize注解拦截失效

文章讲述了在SpringBoot中使用SpringSecurity时,@PreAuthorize注解的拦截失效问题,分析了原因——未启用全局方法级安全,提供了相应的解决方案——在配置类上添加@EnableGlobalMethodSecurity(prePostEnabled=true)注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Security中的@PreAuthorize注解拦截失效

在Spring Boot下Spring Security权限认证时,使用@PreAuthorize注解发现并没有拦截成功。经过排查发现。Spring Security配置类( 也就是继承了WebSecurityConfigurerAdapter的类上面 )上添加@EnableGlobalMethodSecurity(prePostEnabled = true)注解,以启用全局方法级安全性。
具体如下:

package com.javaandvue.config;


import com.javaandvue.common.security.*;
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.method.configuration.EnableGlobalMethodSecurity;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity //添加 @EnableWebSecurity 注解,您可以自定义和配置应用程序的 Web 安全性规则。
//@EnableGlobalMethodSecurity(prePostEnabled = true)  是Spring Security中的一个注解,用于启用全局方法级安全性。
//通过将 prePostEnabled 设置为 true ,它允许使用 @PreAuthorize 和 @PostAuthorize 注解来保护单个方法。 
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtLogoutSuccessHandler jwtLogoutSuccessHandler;


    // 定义白名单URL路径数组
    private static final String URL_WHITELIST[] = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**"
    };

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter=new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }


    //默认密码加密配置
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置应用程序的安全规则
     * 开启跨域资源共享(CORS)功能,并关闭跨站请求伪造(CSRF)攻击防护
     * 配置登录相关设置
     * 禁用会话(session)的创建
     * 配置拦截规则
     * @param http HttpSecurity对象,用于配置应用程序的安全规则
     * @throws Exception 配置过程中可能抛出的异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors() // 开启CORS功能(跨域)
                .and()
                .csrf().disable() // 关闭CSRF攻击防护
                .formLogin() // 配置登录相关设置
                .successHandler(loginSuccessHandler) // 自定义登录成功处理器
                .failureHandler(loginFailureHandler) // 自定义登录失败处理器
                 .and()
                 .logout() // 配置注销设置(如果需要)
                 .logoutSuccessHandler(jwtLogoutSuccessHandler) // 自定义注销成功处理器(如果需要)
                .and()
                //session禁用配置
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 禁用会话的创建(无状态)
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll() // 白名单中的URL路径允许无需身份验证/permitAll放行所有
                .anyRequest().authenticated() // 其他所有请求需要身份验证

        //异常处理配置
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)

        //自定义过滤器配置
        .and()
                .addFilter(jwtAuthenticationFilter());//添加filter
    }

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

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值