SpringBoot 集成 SpringSecurity 配置访问权限

主要依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

方式一:配置antMatchers

自定义配置类

@Configuration
@EnableWebSecurity
public class ConfigMatchersSecurity extends WebSecurityConfigurerAdapter {

    // 加密方式
    private final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 基于内存存储的多用户
        auth.inMemoryAuthentication().withUser("root").password(ENCODER.encode("root")).roles("root").and()
                .withUser("admin").password(ENCODER.encode("admin")).roles("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // antMatchers-不需要验证的请求; permitAll-所有请求
                .antMatchers("/swagger").permitAll()
                // ?-匹配任何单字符;
                .antMatchers("/admin/test?").permitAll()
                // *-匹配0个或者多个字符; hasIpAddress-指定ip下的所有请求
                .antMatchers("/all/list*").hasIpAddress("127.0.0.1")
                // **-匹配0个或者多个目录; hasRole-指定权限下的所有请求
                .antMatchers("/admin/**").hasRole("admin")
                // 注:如果上面满足多个,会根据antMatchers规则较长的来匹配
                ;
        super.configure(http);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return ENCODER;
    }

}

方式二:配置注解
自定义配置类

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

    // 加密方式
    private final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 基于内存存储的多用户
        auth.inMemoryAuthentication().withUser("root").password(ENCODER.encode("root")).roles("root").and()
                .withUser("admin").password(ENCODER.encode("admin")).roles("admin");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return ENCODER;
    }

}

Controller

@RestController
public class EnabledController {

    // 拥有admin权限的才可以访问此路径
    @Secured({"ROLE_admin"})
    @GetMapping(path = "/test1")
    public String test1() {
        return "test1";
    }

    // 拥有admin或root权限的才可以访问此路径
    @Secured({"ROLE_admin", "ROLE_root"})
    @GetMapping(path = "/test2")
    public String test2() {
        return "test2";
    }

    // 拥有admin权限的才可以访问此路径
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping(path = "/test3")
    public String test3() {
        return "test3";
    }

    // 拥有admin或root权限的才可以访问此路径
    @PreAuthorize("hasAnyRole('ROLE_admin','ROLE_root')")
    @GetMapping(path = "/test4")
    public String test4() {
        return "test4";
    }

    // 拥有admin和root权限的才可以访问此路径
    @PreAuthorize("hasRole('ROLE_admin') AND hasRole('ROLE_root')")
    @GetMapping(path = "/test5")
    public String test5() {
        return "test5";
    }

    // returnObject为返回值,返回满足条件才可以访问此路径
    @PostAuthorize("returnObject.length()>=1")
    @GetMapping(path = "/test6")
    public String test6() {
        return "test6";
    }

}

静态获取获取登录信息

// 静态获取UserDetails
public void getUserDetails() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    System.out.println("登录用户: " + userDetails.getUsername());
}
posted @   叕叕666  阅读(98)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示