我们在用java写后端的时候,涉及到权限的话,除了自己写简单的权限管理代码外,还有Spring Security和Shiro两种选择,今天我们探讨下应用Spring Security安全框架下的配置。
众所周知,在Spring Boot中配置Spring Security要先定义一个配置类,该类需要继承WebSecurityConfigurerAdapter,并加上注解@Configuration和@EnableWebSecurity。如果要启用方法级别的权限认证,还需要加上@EnableGlobalMethodSecurity注解。废话少说,进入主题,下面就是最基本的一段配置代码,现在我们一行一行的来解析代码的含义。
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() //权限异常 .exceptionHandling() .authenticationEntryPoint(jwtAuthenticationEntryPoint) .accessDeniedHandler(jwtAuthenticationDeniedHandler) .and() //不创建会话 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //请求过滤 .authorizeRequests() .antMatchers( HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js" ).anonymous() .antMatchers("/swagger-resources/**").permitAll() .antMatchers("/doc.html").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers("/*/api-docs").permitAll() .antMatchers("/actuator/**").permitAll() //放行OPTIONS请求 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() //自定义的匿名访问url放行 .antMatchers(anonymousUrls.toArray(new String[0])).permitAll() //所有请求都需要认证 .anyRequest().authenticated() //防止iframe 造成跨域 .and().headers().frameOptions().disable(); http.addFilterBefore(authorizationTokenFilter, UsernamePasswordAuthenticationFilter.class); }
1、http.csrf().disable() 这行代码是关闭csrf 验证功能,关于Spring Security的csrf功能请查看官网https://docs.spring.io/spring-security/site/docs/4.2.0.BUILD-SNAPSHOT/reference/htmlsingle/#csrf,没有比官网权威的解释了。
2、.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).accessDeniedHandler(jwtAuthenticationDeniedHandler) 这三行代码是对异常的处理,authenticationEntryPoint()是当用户尝试访问安全的REST资源时而不提供任何凭据时,将调用此方法发送401响应;accessDeniedHandler()就是没有访问REST资源的访问权限,返回403响应。
3、.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 这行代码是停用session功能,如何是前后端分离的项目需要配置,如何是传统项目就不需要了。
4、.authorizeRequests() .antMatchers()是对请求的过滤,antMatchers()中带上需要过滤的路径参数或者对HttpMethod方法的过滤参数,由于是链式编程,antMatchers()一般跟上permitAll()方法或者anonymous()方法,anonymous() 是匿名访问,带上token 会报错,permitAll()是允许所有人访问,带不带token都可以。上面贴出的代码中都有具体的注释。
文章中难免会有理解的误区,欢迎各位大神指正!