权限管理工具---springsrcurity
天使总在想象中,魔鬼总在细节处
一、spring security简介
spring security是一个为基于Spring的企业应用系统所提供的声明式安全访问控制解决方式的安全框架。简单来说就是通过访问的控制来实现权限控制。
spring security框架的核心功能是用户认证和用户授权。
二、框架原理
对web紫云啊进行保护最好的办法莫过于Filter(链式),对方法调用进行保护,最好的办法莫过于AOP。
通过各种各样的拦截器来控制权限的访问,从而实现安全。
三、核心组件
1、SecurityContextHolder : 提供对SecurityContext的访问;
2、SecurityContext : 提供Authentication对象和其他可能需要的信息;
3、Authentication : SpringSecurity方法的认证主体;
4、AuthenticationProvider : 主要进行认证操作的类,调用其中的Authentication()方法进行认证操作;
5、AuthenticationManger (接口): 其中可以包含多个AuthenticationProvider;
6、ProviderManger : AuthenticationManger接口的实现类;
7、GrantedAuthority : 对认证主题的应用层面的授权,含当前用户的权限信息,通常使用角色表示;
8、UserDetail : 构建Authentication对象必须的信息,可以自定义,可能需要访问DB得到;
9、UserDetailService : 通过username构建UserDetail对象,通过loadUserByUsername根据userName获取userDetail对象(可以基于自身业务进行自定义的实现,如通过数据库,xml,缓存获取等);
四、自定义安全配置的加载机制
springscurity支持多种认证模式,这些认证模式由第三方提供,或由相关的标准组织。同时springsecurity提供了一组自己的认证功能
自定义一个SpringSecurity安全框架的配置类继承WebSecurityConfigureAdapter,重写其中的configure方法。
4.1、 登陆相关配置类
proteted void configure(HttpSecurity http) throw Exception{
http
.authorizeRequests() //(1)
.antMatchers("/resorces/**","/signup","/about").permitAll() //(2)
.antMatchers("/admin/**").hasRole("ADMIN") //(3)
.antMatchers("/db/**").access("hasRole("ADMIN") and hasRole(""DBA)") //(4)
.anyRequest.authenticated()(5)
.and()
.formLogin();
}
**********************************************************
注释:
(1)http.authorizeRequests()方法有多个子节点,每个macher按照他们的声明顺序执行
(2)我们指定任何用户都可以访问的多个URL
(3)需要拥有ADMIN角色的用户才能访问的URL
(4)需要同时拥有ADMIN和DBA角色的用户才能访问的URL
(5)尚未匹配的任何URL需要用户进行身份验证
4.2、登出相关配置类
proteted void configure(HttpSecurity http) throw Exception{
http
.logout() //(1)
.logouturl("/my/logout") //(2)
.logoutSuccessUrl("/my/index") //(3)
.logoutSuccessHandler(logoutSuccessHandler) //(4)
.invalidateHttpSeccession(true)//(5)
.addLogoutHandler(logoutHandler) //(6)
.deleteCookies(cookieNamesToClear) //(7)
.and()
}
*******************************************************
注释:
(1)提供注销支持
(2)设置触发注销操作的URL(默认是/logout)
(3)注销之后跳转的URL(默认是/login?logout)
(4)如果指定了这个选项,那么logoutSuccessUrl()的设置会被忽略,成功注销后被调用,进行重定向或者转发相应的目的地
(5)指定是否在注销时让HttpSession无效,默认设置为true
(6)执行各种必要的清理
(7)允许指定在注销成功时将移除的cookie
4.3、 访问web资源的用户的权限认证
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
}
//可以设置为从内存中读取相关信息,也可以自定义一个userDetailService为bean定义身份验证
来源:CSDN
作者:骑猪仗剑闯天下
链接:https://blog.csdn.net/weixin_42267415/article/details/103823636