• 【Spring Security】安全框架学习(十四)


    6.2 基于配置的权限控制

    我们之前的权限控制都是在对应的资源上面,加上注解去进行一个权限的配置。实际上spring security还允许我们在配置类中进行配置权限。例如我们之前就对login接口进行了一个相应的权限控制。

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        
        //创建BCryptPasswordEncoder注入容器
    	@Bean
    	public PasswordEncoder passwordEncoder(){
    		return new BCryptPasswordEncoder();
        }
        
        @Bean
        @Override
    	protected void configure(HttpSecurity http) throws Exception {
    		http
    			//关闭csrf,前后端分离项目必须写
    			.csrf().disable()
    			//前后端分离不能使用session,这里不通过session获取SecurityContext
    			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    			.and()
    			.authorizeRequests()
    			//对于登录接口允许匿名访问
    			.antMatchers("/user/login").anonymous()
                //6.2小节新增内容,添加权限控制,根据需要自行添加修改,除了hasAuthority,其他方法也能使用
                .antMatchers("/test").hasAuthority("test")
    			//除上面外的所有请求全部需要鉴权认证
    			.anyRequest().authenticated();
            
            //配置异常处理器
            http.exceptionHandling()
                //认证失败处理器
                .authenticationEntryPoint (authenticationEntryPoint)
                //授权失败处理器
    			.accessDeniedHandler(accessDeniedHandler);
            
                    
        //新增加的过滤器代码,需要传入两个对象,一个文档对象,一个字节码对象(指定添加到哪个过滤器对象之前)
        	http
                .addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
            
            //允许跨域
            http.cors();
    	}
    
        
        @Bean
        @Override
    	public AuthenticationManager authenticationManagerBean() throws Exception {
    		return super.authenticationManagerBean();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
  • 相关阅读:
    python爬虫中json数据与python数据相互转换
    故障分析 | MySQL 节点宕机分析一例
    【示例】如何使用Pytorch堆叠一个神经网络
    Spring中Bean的作用域
    Redis-主从复制、Sentinel、Cluster集群【随笔四】
    SaaSBase:什么是企业微信?
    gitlab runner 不清理云端已经删除的tag和branch问题记录
    毕业设计选题之Java+springboot线上蔬菜销售与配送系统(源码+调试+开题+lw)
    selenium webdriver 防爬问题 C#
    centos下gmssl编译
  • 原文地址:https://blog.csdn.net/qq_38594872/article/details/126813712