Spring Security权限控制注解

介绍

除了在配置类中对 url 配置权限控制,还可以通过注解进行权限控制

开启权限控制注解

在配置类上加上注解:

@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true,jsr250Enabled = true)
  • securedEnabled=true 开启spring security的权限控制注解
  • prePostEnabled = true 开启权限控制注解,支持 el表达式
  • jsr250Enabled = true 开启java250权限控制注解

完整代码

package top.malaoshi.stdsecurity.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.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import top.malaoshi.stdsecurity.security.SLoginService;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true,jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


//    指定密码编码器为:BCryptPasswordEncoder
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

//    登录service,自定义实现
    @Resource
    private SLoginService sLoginService;

//    指定使用自定义的登录service,并指定密码编码器
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sLoginService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/js/**","/img/**");//绕开所有的filter,直接跳过验证
    }

    //    安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
//                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
//                .and()

                .authorizeRequests()//url权限配置
//                .antMatchers("/index.html").permitAll() // 匹配这些路径可以所有人访问
                .antMatchers("/dept/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("admin")
                .anyRequest().authenticated()
                .and()

                //login部分
                .formLogin()
                .loginPage("/login.html")//指定登录页面。所有url前面必须写/,否则报错 'xxx' is not a valid forward URL
//                .usernameParameter("user")//登录页面用户名控件name值
//                .passwordParameter("pwd")//登录页面密码控件name值
                .loginProcessingUrl("/login")//security提供的处理登录url,默认是/login
//                .successForwardUrl("/index.html")//登录成功后跳转的页面,需要额外处理才能使用,否则页面会提示错误
                .defaultSuccessUrl("/index.html")//登录成功后重定向的页面
                .failureUrl("/login_fails.html")//登录失败跳转的页面
//                .failureForwardUrl("/login_fails.html")//登录失败不会转发
                .permitAll()//让login部分的url可以任意访问
//
//                //logout部分
                .and()
                .logout()//退出登录需要提交post请求
                .logoutSuccessUrl("/login.html")//退出成功访问的页面
                .invalidateHttpSession(true)//清空session
                .permitAll();//让logout部分的url可以任意访问

    }

}

权限注解的位置

可以加在Controller类和方法上,Service类和方法上

@Secured

spring security的权限控制注解

必须要设置:securedEnabled=true,如下:

@EnableGlobalMethodSecurity(securedEnabled=true)

例子

@RestController
public class DepController {
    //权限注解,有"ROLE_admin"或"mng_dept"权限时才能访问
    @Secured({"ROLE_admin","mng_dept"})
    @RequestMapping("/dept")
    public List showDepList(){
        List<String> list=new ArrayList<String>();
        list.add("开发部");
        list.add("人力资源部");
        list.add("产品经理部");
        list.add("CEO");

        return list;
    }
}

注意

如果是角色,那么前面要加ROLE_前缀。
配置类中的角色判断是:.antMatchers("/dept/**").hasRole("admin"),是没有ROLE_前缀的

@RolesAllowed

java权限控制注解

必须设置:jsr250Enabled = true,如下:

@EnableGlobalMethodSecurity(jsr250Enabled = true)

例子

@RestController
public class DepController {

    @RolesAllowed({"ROLE_admin","mng_dept"})
    @RequestMapping("/dept")
    public List showDepList(){
        List<String> list=new ArrayList<String>();
        list.add("开发部");
        list.add("人力资源部");
        list.add("产品经理部");
        list.add("CEO");

        return list;
    }
}

注意

如果是角色,那么前面要加ROLE_前缀。
配置类中的角色判断是:.antMatchers("/dept/**").hasRole("admin"),是没有ROLE_前缀的

@PreAuthorize

支持 el表达式

必须设置prePostEnabled = true,如下:

@EnableGlobalMethodSecurity(prePostEnabled = true)

例子

@RestController
public class DepController {

    @PreAuthorize("hasAnyAuthority('ROLE_admin','mng_dept')")
    @RequestMapping("/dept")
    public List showDepList(){
        List<String> list=new ArrayList<String>();
        list.add("开发部");
        list.add("人力资源部");
        list.add("产品经理部");
        list.add("CEO");

        return list;
    }
}

@PreAuthorize("hasAnyAuthority('ROLE_admin','mng_dept')")注解里面支持hasAnyAuthority()等方法,配置类权限控制方法,该注解也都支持


原文出处:/show_1EF60ukLATwO.html