spring security是一个多方面的安全认证框架,提供了基于JavaEE规范的完整的安全认证解决方案。并且可以很好与目前主流的认证框架(如CAS,中央授权系统)集成。使用spring security的初衷是解决不同用户登录不同应用程序的权限问题,说到权限包括两部分:认证和授权。认证是告诉系统你是谁,授权是指知道你是谁后是否有权限访问系统(授权后一般会在服务端创建一个token,之后用这个token进行后续行为的交互)。
spring security提供了多种认证模式,很多第三方的认证技术都可以很好集成:
- Form-based authentication (用于简单的用户界面)
- OpenID 认证
- Authentication based on pre-established request headers (such as Computer - Associates Siteminder)根据预先建立的请求头进行验证
- JA-SIG Central Authentication Service ( CAS, 一个开源的SSO系统)
- Java Authentication and Authorization Service (JAAS)
这里只列举了部分,后面会重点介绍如何集成CAS,搭建自己的认证服务。
在spring boot项目中使用spring security很容易,这里介绍如何基于内存中的用户和基于数据库进行认证。
准备
pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("rhwayfun").password("1209").roles("USERS")
.and().withUser("admin").password("123456").roles("ADMIN");
//auth.jdbcAuthentication().dataSource(securityDataSource);
//auth.userDetailsService(userDetailsService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置安全策略
//.antMatchers("/","/index").permitAll()//定义/请求不需要验证
.anyRequest().authenticated()//其余的所有请求都需要验证
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.permitAll()
.and()
.logout()
.logoutSucc