搭建SpringSecurity环境
1. 项目初始化
同样的使用Spring Initializr
进行初始化,并添加依赖组件Eureka Discovery
和security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 修改配置文件
spring:
application:
name: admin
server:
port: 8002
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
3. 新建安全适配器SecurityConfig
这里建个config包,并新建个SecurityConfiguration
继承WebSecurityConfigurerAdapter
,重写3个configure方法
configure(AuthenticationManagerBuilder auth)
身份验证管理生成器configure(HttpSecurity http)
HTTP请求安全处理configure(WebSecurity web)
WEB安全
这里我们做个简单的http验证
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 以"about"开头的全部放行
.antMatchers("/about").permitAll()
// 以"admin"开头的需要"ADMIN"权限
.antMatchers("/admin").hasRole("ADMIN")
// 以"db"开头的需要"ADMIN"或者"DBA"中的任意一个权限
.antMatchers("/db").hasAnyRole("ADMIN","DBA")
// 以"api"开头的必须同时拥有"ADMIN"和"DB"权限
.antMatchers("/api").access("hasRole('ADMIN') and hasRole('DBA')")
// 其它URL全部要求身份验证
.anyRequest().authenticated()
.and()
// 设置登录页面
.formLogin()
.loginPage("/login")
// 登录成功跳转的页面
.defaultSuccessUrl("/index")
// 登录失败跳转的页面
.failureUrl("/error")
.permitAll()
.and()
// 启用cookie存储用户信息,设置有效期(7天)和key
.rememberMe().tokenValiditySeconds(7*24*60*60).key("mykey")
.and()
.logout()
// 指定登出页面
.logoutUrl("/logout")
// 指定登出成功的页面
.logoutSuccessUrl("/index")
.permitAll();
}
}
注意这里必须要加上
@Configuration
和@EnableWebSecurity
注解以开启安全认证并表明是一个配置类
and()
返回一个securityBuilder
对象,formLogin()
和httpBasic()
是授权的两种方式。