SpringSecurity讲解与实践(代码仅供学习)
- 下载本文的SpringSecurity实战代码链接:https://download.csdn.net/download/shooter7/37060883
说明
SpringSecurity讲解与实践,主要用于实现以下的功能:
- 用户认证、授权
- 注销、权限限制
- 记住我、首页定制
由于是SpringBoot的一个现成的框架,所以我们需要在项目的config的文件夹下面新建一个SecurityConfig配置的类,用于实现配置以上的功能,具体的一些参数需要我们多看看源码。
安全
- 做安全,应该在网站设计之初考虑的,因为架构一旦确定,才考虑安全,会改动比较多的代码
SpringSecurity
- 功能权限
- 访问权限
- 菜单权限
- 之前是用的拦截器、过滤器:大量的原生代码,过于冗余
配置类关键代码
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问,但是功能页只能有权限的人才能访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限会到登录页面,需要开启登录的页面
//定制登录页面
http.formLogin().loginPage("/toLogin").usernameParameter("ugh").passwordParameter("upwd").loginProcessingUrl("/login");
http.formLogin();
//注销,开启了注销
http.csrf().disable(); //关闭csrf(防跨站攻击)功能,登出失败可能存在的原因
http.logout().logoutSuccessUrl("/");
//开启记住我的功能,默认保存2周的时间,自定义接受前端的参数
http.rememberMe().rememberMeParameter("remember");
}
//认证 springboot2.1x 可以直接使用
//密码编码:PasswordEncoder
//在Spring Security5.0+中新增了很多加密的方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//数据正常在数据库中被读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3","vip1")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
代码实践
- 代码实践中有简单的登录页面,以及登录进去的首页,首页中有不同等级会员才会有的模块,需要进行用户的认证和授权才能够进入,以及实现一些权限的限制,注销,记住我、首页定制等的功能。
注:如果出现不同权限进去还是能看到所有的level。那就可能是Springboot的版本的问题,版本过高,我们可以在pom.xml将其版本调为2.0.9.RELEASE。