springboot集成SpringSecurity
简介
市面上存在比较有名的:Shiro,Spring Security !
一般来说,常见的安全管理技术栈的组合是这样的:
- SSM + Shiro
- Spring Boot/Spring Cloud + Spring Security
项目创建
1. 新建springboot项目,增加web和thymeleay模块
2. 导入相关静态资源
3. controller跳转
@Controller
public class RouterController {
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
4. 测试
谁都可以访问该网站的任意模块,我们使用 Spring Security 增加上认证和授权的功能进行少量的配置,即可实现强大的安全管理!
springSecurity学习
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1. spring security实现认证
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用
@EnableWebSecurity // 开启WebSecurity模式
public class WebSecurityConfig 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()默认走他自己的路径, http.formLogin().loginPage("/toLogin");可以自定义
http.formLogin().loginPage("/toLogin");
http.logout().logoutSuccessUrl("/index");
//开启记住我, cokkie默认保存两周 , 在login.html有个checkbox remember
http.rememberMe().rememberMeParameter("remember");
}
}
2. spring security实现授权
授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//passwordEncoder:密码编码
//在spring security5.0+中新增了很多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从内存中读,也可以从数据库中读取 auth.jdbcAuthentication()
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("wang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("xiaoman").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}

浙公网安备 33010602011771号