springboot使用注解版的SpringSecurity做权限管理

1、引入maven

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

项目结构
在这里插入图片描述
2、在config包下面创建一个配置类SecurityConfigTest继承WebSecurityConfigurerAdapter

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(password());

    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义登录跳转的页面及角色权限
     *
     * @param http
     */
    @Override
    protected void configure(HttpSecurity http) {
        try {
            //配置退出的路径
            http.logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/test/hello")
                    .permitAll();
            //配置登录
            http.formLogin()
                   .loginPage("/login.html")//登录页面设置
                   .loginProcessingUrl("/user/login")//登录访问路径
                   .defaultSuccessUrl("/test/index")//登录成功之后,跳转的路径
                    .and().authorizeRequests()
                    .antMatchers("/", "/test/hello", "/test/index", "/user/login").permitAll()//设置哪些路径是不需要拦截的
                   .antMatchers("/test/index").hasAnyAuthority("admins,manager")//hasAnyAuthority基于资源的权限控制,匹配任意一个符合条件的即可
//                    .antMatchers("/test/role").hasAnyRole("sale")//基于角色的权限控制,匹配任意角色即可
                    .anyRequest().authenticated()
                    .and().csrf().disable();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

一般建议使用的是对资源进行授权,不建议对角色进行授权
3、创建MyUserDetailService实现Security里面的UserDetailsService接口

@Service("userDetailService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = userMapper.selectOne(wrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //角色控制,需要添加一个前缀ROLE
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
    }
}

基于角色控制的时候需要在角色的前面添加一个ROLE_不然识别不了。

mapper编写

@Mapper
@Repository
public interface UserMapper extends BaseMapper<Users> {
}

以上是介于配置类的方式来进行权限的管理,还以使用注解的方式来做权限管理
开启注解模式

@SpringBootApplication
//securedEnabled = true,开启security注解模式,prePostEnabled = true,在方法之前和之后执行校验
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityDemoApplication.class, args);
    }

}

创建配置类

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(password());

    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义登录跳转的页面及角色权限
     *
     * @param http
     */
    @Override
    protected void configure(HttpSecurity http) {
        try {
            //配置退出的路径
            http.logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/test/hello")
                    .permitAll();
            //配置登录
            http.formLogin()
                    .and().authorizeRequests()
                    .antMatchers("/", "/test/hello", "/test/index", "/user/login").permitAll()//设置哪些路径是不需要拦截的
                    .anyRequest().authenticated()
                    .and().csrf().disable();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

在Ctroller中添加注解


@RestController
@RequestMapping("/test")
public class HelloController {

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/role")
    public String role() {
        return "role";
    }

    @GetMapping("/update")
//    @Secured({"ROLE_sale","ROLE_manager"})//基于角色可以访问
    @PreAuthorize("hasAnyAuthority('admins') and hasAnyAuthority('read_account') ")//基于资源的权限访问,在方法执行之前进行校验
//    @PostAuthorize("hasAnyAuthority('admins')") //基于资源的权限访问,在方法执行之后进行校验
    public String update() {
        return "update";
    }
}

如果需要对返回的结果进行过滤后返回,可以使用@PostFilter()
在返回的集合中,只有username=admin1的数据才会返回
在这里插入图片描述
如果需要对传入发参数集合进行筛选之后才调用方法,可以使用@PreFilter(),
在参数集合list中,只有id等于偶数的才能访问
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: SpringBoot 3.0可以使用Spring Security来实现安全认证和授权控制,可以通过在Spring Boot项目的Maven依赖中添加spring-boot-starter-security依赖来实现。 ### 回答2: 要集成Spring SecuritySpring Boot 3.0中,可以按照以下步骤操作: 1. 在pom.xml文件中添加Spring Security的依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建一个配置类,例如SecurityConfig,该类需要继承自WebSecurityConfigurerAdapter,并使用@EnableWebSecurity注解启用Spring Security配置。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() // 设置公开访问的URL .anyRequest().authenticated() // 其他URL需要认证 .and() .formLogin() // 使用表单登录 .and() .logout().permitAll(); // 允许注销 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // 使用内存中的用户进行身份认证 .withUser("admin").password("{noop}password").roles("ADMIN") .and() .withUser("user").password("{noop}password").roles("USER"); } } ``` 3. 在configure(HttpSecurity http)方法中配置URL的访问权限,设置公开访问的URL和需要认证的URL。这里演示了两个简单的示例,所有以/public/开头的URL都允许公开访问,其他URL需要认证。 4. 在configure(AuthenticationManagerBuilder auth)方法中配置用户的身份认证信息。这里使用了内存中的用户,用户名为admin和user,密码为password,分别具有ADMIN和USER角色。 5. 可以根据自己的需求进行进一步配置,例如添加自定义的登录页面、自定义登录成功/失败的处理逻辑等。 通过以上步骤,就可以将Spring Security集成到Spring Boot 3.0中。需要注意的是,这只是一个简单的示例,实际应用中可能需要根据实际情况进行调整和配置。 ### 回答3: 要将Spring Boot 3.0集成Spring Security,需要执行以下步骤: 1. 首先,在项目的pom.xml文件中添加Spring Security的依赖项。可以在Spring Boot官方文档中找到最新本的依赖项坐标。 2. 创建一个继承自WebSecurityConfigurerAdapter的配置类,并使用@EnableWebSecurity注解标记该类。这个配置类将用于定义安全规则。 3. 在配置类中,覆盖configure(HttpSecurity http)方法来配置安全策略。这个方法允许你定义哪些URL路径需要被保护,哪些路径可以被公开访问,以及如何进行登录认证等。 4. 如果需要自定义登录页面,可以创建一个继承自WebMvcConfigurer的配置类,并覆盖addViewControllers方法来注册自定义登录页面的URL路径。 5. 如果需要自定义认证逻辑,可以创建一个实现UserDetailsService接口的自定义用户服务类,并将其注册为Spring组件。在configure方法中使用userDetailsService()方法来指定这个自定义用户服务类。 6. 可以使用@EnableGlobalMethodSecurity注解来启用全局方法级别的安全性,并设置相关的注解。 7. 最后,可以使用SecurityContextHolder来实现在应用程序中获得当前用户的信息。 通过以上步骤,就可以将Spring Boot 3.0和Spring Security集成起来。这样就可以保护应用程序的URL路径,实现用户认证和授权的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量化接口stockapi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值