1.概述
spring security是能够在Web请求级别和方法调用级别处理身份验证(认证who are you?)和授权(批准what can you do?)的安全框架
spring security从两个角度解决安全问题
1.使用Servlet规范中的Filter保护Web请求并限制URL级别的访问;
2.使用spring Aop保护方法调用,借用动态代理和使用通知确保只有在具有相应权限的用户才能访问被保护的方法
今天先来明白一下身份验证,spring security身份验证有两种,Http认证和表单认证。
2.http认证
学习之前,需要自己创建一个springboot项目,我将在springboot项目上演示接下来的操作。可以用idea直接创建一个spring项目,它会帮你创建application.properties文件和启动类。
启动启动类,会在控制类输出密码
输入http://localhost:8083/http/index
地址栏请求变成
/login界面
输入user和控制台打印的密码点击登录,再次重定向到你访问的url
上面的过程就是spring security的http登录认证模式
3.formLogin登录认证模式
写一个类继承WebSecurityConfigurerAdapter,重写里面的三个confiure方法
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
/**
* 登录验证及资源访问的权限规则
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//http认证
/*http.httpBasic().and().authorizeRequests().anyRequest().permitAll().and();*/
//表单认证
// 表单登录,而不是httpBasic
.formLogin()
.loginPage("/mylogin.html")//用户未登录时,访问任何资源都转跳到该路径,即登录页面
.loginProcessingUrl("/validate/mylogin")//登录表单form中action的地址,也就是处理认证请求的路径
.defaultSuccessUrl("/index")//登录认证成功后默认转跳的路径
.and()
.authorizeRequests()
.antMatchers("/mylogin.html","/hello/*").permitAll()///不需要通过登录验证就可以被访问的资源路径
.antMatchers("/biz1").hasAnyAuthority("biz1") //前面是资源的访问路径、后面是资源的名称或者叫资源ID
.antMatchers("/biz2").hasAnyAuthority("biz2")
.antMatchers("/syslog").hasAnyAuthority("syslog")
.antMatchers("/sysuser").hasAnyAuthority("sysuser")
.anyRequest().authenticated();
/**
* 用户及角色信息配置
* @param auth
* @throws Exception
*/
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("123456"))
.roles("user").and()
.withUser("admin").password(passwordEncoder().encode("123456"))
//.authorities("sys:log","sys:user")
.roles("admin")
.and()
.passwordEncoder(passwordEncoder());//配置BCrypt加密
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* 开放静态资源
* @param web
*/
@Override
public void configure(WebSecurity web) {
//将项目中静态资源路径开放出来
web.ignoring().antMatchers( "/css/**", "/fonts/**", "/img/**", "/js/**");
}
}