SpringSecurity

        Spring Security是为基于Spring的应用程序提供声明式安全保护的安全性框架,它提供了完整的安全性解决方案,能够在web请求级别和方法调用级别处理身份证验证和授权。因为基于Spring框架,所以Spring Security充分利用了依赖注入和面向切面的技术,不要配置filter或者是编写复杂的拦截器来实现权限的控制与验证。

       首先需要引入spring-boot-starter-security这个jar包,然后来继承WebSecurityConfigurerAdapter这个类来重写其中的方法,通过添加@EnableWebSecurity注解来作为身份验证的入口。

  通过重写configure(HttpSecurity http)方法来编写认证策略:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/chl1/**").hasRole("chl1")//拥有chl1权限的可以访问chl1下的内容
.antMatchers("/chl2/**").hasRole("chl2")
.antMatchers("/chl3/**").hasRole("chl3");

  
   http.crsf().disable();//防止跨域攻击
http.formLogin().loginPage("/login");//配置当认证错误的时候(login?error)会跳转的登录界面
}

  通过重写configure(AuthenticationManagerBuilder auth)方法来编写认证信息:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//一般需要添加密码的转码规则,否则会提示没有转码的错误,这个转码规则有几种方法提供,可以自行查看源码使用

            .withUser("chl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("tlj").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}
posted @ 2020-06-15 01:38  吃饼大王  阅读(51)  评论(0)    收藏  举报