本文主要是介绍springboot配置springsecurity的大概步骤。
1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2 新建SecurityConfig类继承自WebSecurityConfigurerAdapter,此类为Spring Security提供的Web应用安全配置的适配器,主要重写两个方法
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
第一个方法常用于http请求的认证授权等配置;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(customAuthenticationSucessHandler) // 处理登录成功
.failureHandler(customAuthenticationFailureHandler) // 处理登录失败
.and()
.authorizeRequests()
.antMatchers("/login.html").permitAll()
.anyRequest()
.authenticated()
.and().csrf().disable();
}
第二个方法则是自定义登录验证的操作,比如说根据用户名从数据库中获取到用户数据并和密码进行匹配来判断用户名和密码是否正确的程序,一般都会将这部分程序放到一个继承于UserDetailsService的类中。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.userDetailsService(new CustomUserDetailsService());
auth.authenticationProvider(new CustomAuthenticationProvider());
}