SpringSecurity要点
关于启用
- 传统Spring全注解方式下,需要加入 @EnableWebSecurity
- SpringBoot只需配置 spring-boot-starter-security 依赖即可自动启用
关于配置
SpringSecurity通过读取SecurityConfigurer接口数据实现配置。为了方便使用,Spring为Web项目提供了默认空实现:WebSecurityConfigurerAdapter。继承它,开发者可以获得SpringSecurity默认的安全功能,覆盖它即可实现自定义安全方案。
public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigurer<WebSecurity> {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//方法一
}
public void configure(WebSecurity web) throws Exception {
//方法二
}
protected void configure(HttpSecurity http) throws Exception {
//方法三
}
}
这三个方法是WebSecurityConfigurerAdapter里面最重要的方法。
方法一
protected void configure(AuthenticationManagerBuilder auth) throws Exception
这个方法用于配置用户实现用户账号信息校验。包括:用户名、密码、权限等等。主要是user-details机制。这是用户使用Web服务的第一步。
AuthenticationManagerBuilder auth
校验管理器,用于比对用户信息,告诉SpringSecurity是否通过校验。
示例程序,参考:hello-security
这里需要注意的是,Spring5 的Security中必须使用密码编码器,否则会报错
方法三
经过方法一的验证,用户信息是合法有效的,但是这并不意味着用户就可以访问Web的所有资源了。针对请求的访问拦截验证就是在方法三实现的。
请求拦截验证的三个基本元素是:用户、权限,URL
protected void configure(HttpSecurity http) throws Exception {
logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
http.authorizeRequests()
.anyRequest()
.authenticated()
.and().formLogin()
.and().httpBasic();
}
这个是WebSecurityConfigurerAdapter里面默认的实现:
authorizeRequests:返回所有通过用户认证的请求
anyRequest:返回所有用户请求
authenticated:后面的方法将对所有认证成功的用户生效
formLogin:使用Spring Security默认的登录页面
httpBasic:启用HTTP基础认证
用户身份认证
用户身份认证是获取Web服务的第一步。说白了就是校验用户凭据,对于大多数Web服务来说就是校验用户名和密码。
SpringSecurity内置提供了多种用户认证方式,常用的是如下三种:
- 基于内存的身份认证:简单,多用于调试,不常见于企业级应用
- 基于数据库的身份认证:简单,不用写代码,自动完成比对工作。需要标准数据库配套使用,不灵活。
- 自定义用户认证服务:自行实现UserDetailsService接口,并注入。
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
提供用户细节,如果返回null则表明用户身份认证失败。
hello-security 实现的就是这种方式。
请求校验
用户身份认证只是第一步,校验通过之后,需要根据用户角色(ROLE)对其试图访问的URL进行鉴权,即请求拦截验证。再次重复,请求拦截验证的三个基本元素是:用户、权限,URL。
SpringSecurity机制下,需要通过实现上文提到的方法三来完成。