security
-
2023年4月12日发(作者:国信金太阳炒股软件下载)SpringSecurity知识点归纳⼀
SpringSecurity:⼀个⾝份验证和访问控制框架。
简介:
基于JavaEE的企业软件应⽤程序提供全⾯的安全服务。特别强调⽀持使⽤SpringFramework构建的项⽬。
最⼩的SpringSecurity的maven依赖:
ty
spring-security-web
E
springboot项⽬添加该依赖后并直接启动后,访问任何⼀个url都会弹出验证框。默认⽤户名为user、密码在控制台显⽰。
创建SpringSecurity配置类
red;tion.*;
rs.*;
uration.*;
@Configuration@EnableWebSecurity
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@Autowired
publicvoidconfigureGlobal(AuthenticationManagerBuilderauth)throwsException{auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");//为单个⽤户配置内存⾝份验证}
protectedvoidconfigure(HttpSecurityhttp)throwsException{http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}}
ureGlobal⽅法:
①对应⽤程序中的每个url进⾏⾝份验证②⽣成登录表单
③允许账户名为user、密码为password的⽤户使⽤基于表单的⾝份验证进⾏⾝份验证④允许⽤户注销
ure(HttpSecurityhttp)⽅法:
①确保对我们的应⽤程序的任何请求都要求⽤户进⾏⾝份验证
②允许⽤户使⽤基于表单的登录进⾏⾝份验证
③允许⽤户使⽤HTTP基本⾝份验证进⾏⾝份验证④and()类似分隔符
3.默认有个⾃带的登录作⽤url,但是⼤多数程序希望⽤⾃⼰的登录页⾯:
protectedvoidconfigure(HttpSecurityhttp)throwsException{http
.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")//指定登录页⾯的位置
.permitAll();//授权所有⽤户登录页⾯的权限
.failureUrl("/login-error")//指定登录出错请求}
4.通过izeRequest()来添加多个⼦项指定url的⾃定义要求:
protectedvoidconfigure(HttpSecurityhttp)throwsException{http
.authorizeRequests()//该⽅法有多个⼦节点,每个匹配器按其声明的顺序进⾏考虑
//url以这⼏个地址开头的,任何⽤户都可以访问该请求.antMatchers("/resources/**","/signup","/about").permitAll()
//以“/admin/”开头的url都被认为⽤户具有“ROLE_ADMIN”⾓⾊,hasRole⽅法省略了"ROLE_"前缀.antMatchers("/admin/**").hasRole("ADMIN")
//以“/db/开头的url要求⽤户同时具有“ROLE_ADMIN”和“ROLE_DBA”⾓⾊
.antMatchers("/db/**").access("hasRole('ADMIN')andhasRole('DBA')")
.anyRequest().authenticated()
.and()//...
.formLogin();}
form-login属性详解
-page⾃定义登录页url,默认为/login
-processing-url登录请求拦截的url,也就是form表单提交时指定的action(要⼀致)
t-target-url默认登录成功后跳转的url
-use-default-target是否总是使⽤默认的登录成功后跳转url
tication-failure-url登录失败后跳转的url
me-parameter⽤户名的请求字段默认为userName
rd-parameter密码的请求字段默认为password
tication-success-handler-ref指向⼀个AuthenticationSuccessHandler⽤于处理认证成功的请求,不能和default-target-url还有always-use-default-target同时使⽤
tication-success-forward-url⽤于authentication-failure-handler-ref
tication-failure-handler-ref指向⼀个AuthenticationFailureHandler⽤于处理失败的认证请求
tication-failure-forward-url⽤于authentication-failure-handler-ref
tication-details-source-ref指向⼀个AuthenticationDetailsSource,在认证过滤器中使⽤
-
security