若依权限管理框架
Spring Security介绍
- Spring Security是spring的权限控制框架,主分为
认证
和授权
认证
:是否能进入
(登录
)授权
:是否有权限访问对应的资源
(controller能否访问
)
Spring Security 配置
配置类上有一个非常重要的注解
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
- 我们自己的配置类是继承了Spring Security原本框架提供的基类,此基类中 有很多
默认 的 配置方法
,极大地简化了我们配置操作- 如果说 想要
自定义某些配置
,你就需要重写 对应的方法
认证
方法的重写
- 但是这个方法解决的无法依赖注入的问题
重写配置相关的方法
加入可以匿名访问的资源
- 找带有
Anonymous
注解的
这个类一般是加在 Controller方法上
配置哪些是可以放行的,哪些需要拦截的
- 禁用响应的标头
- 认证失败的处理
- 基于token,不使用session
- 放行静态资源
- 拦截其他请求
- 防止页面被IFrame嵌套使用
httpSecurity
// CSRF禁用,因为不使用session
.csrf().disable()
// 禁用HTTP响应标头
.headers().cacheControl().disable().and()
// 认证失败处理类 unauthorizedHandler通过IOC容器注入
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session STATELESS 代表任何请求都不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 上面的配置都是全局配置,是基于HttpSecurity 进行链式编程的
// 过滤请求
.authorizeRequests()
// 下面的配置是针对认证请求的配置,是基于ExpressionInterceptUrlRegistry进行链式编程的
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/register", "/captchaImage").permitAll()
// 静态资源,可匿名访问
.antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
.antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
//禁用 HTTP 响应头中的 `X-Frame-Options`。`X-Frame-Options` 是一个 HTTP 响应头,用于防止网页被嵌入到 `iframe` 中,从而防止点击劫持攻击。
.headers().frameOptions().disable();
其他配置
// 添加Logout filter logoutSuccessHandler是通过IOC容器依赖注入的
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter authenticationTokenFilter是通过IOC容器依赖注入的 UsernamePasswordAuthenticationFilter是SpringSecurity默认的登录验证过滤器
// 会将用户的认证对象放入SecurityContextHolder中
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
// 在认证过滤器之前添加CORS filter 处理跨域请求
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
// 在退出过滤器之前添加CORS filter 处理跨域请求
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
用户认证的详细逻辑
密码加密之后传递给详细的接口,进行认证
/**
* 身份认证接口
*/
// 这个configure方法是用来配置用户信息服务的,即配置用户的登录信息 和上面的configure方法不是同一个方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
// 通过userDetailsService方法注入自定义的用户认证逻辑
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
全局就这么一个实现类