spring security:认证和授权
pom.xml导包
<!-- 导入spring security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
之后将静态文件导入到static和template下
编写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;
}
}
此时设置了一系列url下的页面路径,然而此时每个level下的资源是可以随时访问的,但这显然不符合我们的需求,此时就要使用到springsecurity的配置类来自定义认证和授权
自定义授权
@EnableWebSecurity代表使用了spring-security的功能
创建一个类继承于WebSecurityConfigurerAdapter类,
这是一个拦截器的功能类,然后重写方法,进行自定义。
@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();
//开启了注销功能
http.logout().logoutSuccessUrl("/");
}
这里格式都是统一的,是由antMatchers()函数指定url路由,在用hasRole()寒食进行授权,指定访问者。
自定义认证
同样是在继承于WebSecurityConfigurerAdapter类的类下重写方法configure进行认证,给用户给予身份。
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("chen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
同样格式固定,withUser()指定用户名,password()指定密码,roles()赋予用户身份。值得注意的是,完成一个认证后,使用and()进行下一个认证的连接。
password()要进行加密,可以使用
new BCryptPasswordEncoder().encode(“123456”)
的形式进行编码,在开始使用指定编码的方式,使用**passwordEncoder(new BCryptPasswordEncoder())**来告诉security系统