Spring Security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot1.X版本依赖Security 4.X,默认HttpBasic验证模式;Spring Boot2.X版本依赖Security 5.X,默认表单模式。
角色~权限
角色和权限一视同仁,都存储在auhtorities表,角色带有ROLE_
前缀。
关于说明参见:GrantedAuthority
HttpBasic模式
提供一种“防君子不防小人”的登录验证,security.basic.enabled
已过时,需手动开启
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()//开启httpbasic认证
.and().authorizeRequests().anyRequest().authenticated();//所有请求都需要登录认证才能访问
}
}
默认用户名user
,密码在控制台有打印。或自定义
spring:
security:
user:
name: user_1
password: snant
Http请求中使用Authorization作为一个Header,值为Basic Base64(name:password)
HttpBasic模式登录认证
formLogin登录认证模式
定制登录页面,
- formLogin:登录验证逻辑
- authorizeRequests:资源访问权限
通过重写WebSecurityConfigurerAdapter的configure(HttpSecurity http)
方法
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //禁用跨站csrf攻击防御
.formLogin()...
.and()
.authorizeRequests()...
}
}
对于静态资源的权限开放,重写WebSecurityConfigurerAdapter的configure(WebSecurity web)
方法
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers( "/css/**", "/fonts/**", "/img/**", "/js/**");
}