spring security认证和授权流程
spring security
spring框架中的一个安全框架,它提供了全面的安全解决方案,包括认证
(Authentication)和授权(Authorization)
下面我介绍下spring security认证和授权的流程
认证(Authentication)
认证是确定用户身份的过程,在Spring Security中,认证流程通常涉及以下几个步骤:
a. 请求拦截
当用户尝试访问受保护的资源时,Spring Security的过滤器会拦截请求。
b. 认证请求
表单登录:用户通过提交用户名和密码的表单进行登录
HTTP Basic: 用户通过HTTP Basic认证头发送用户名和密码
OAuth2/OpenID Connect:使用OAuth2或OpenId Connect协议进行认证
JWT(JSON Web Tokens):通过携带JWT令牌进行认证
c. 认证处理
-
UserDetailsService:Spring Security通过
UserDetailsService
接口加载用户详情。 -
PasswordEncoder:对提交的密码进行加密,并与数据库中的加密密码进行比较。
-
AuthenticationManager:管理认证过程,验证用户名和密码的正确性。
d. 成功与失败
-
如果认证成功,
Authentication
对象将被创建并存储在SecurityContextHolder
中。 -
如果认证失败,将抛出
AuthenticationException
。
授权(Authorization)
授权是在用户身份确认后,决定用户是否有权限访问特定资源的过程,授权流程通常涉及以下几个步骤:
a . 访问决策
-
AccessDecisionManager:决定用户是否有权访问受保护的资源。
-
Access Control Lists (ACLs):使用ACLs来控制访问权限。
-
Expression-based access control(使用Spring Security的表达式语言,例如
@PreAuthorize
注解)。
b. 方法安全性和URL安全性
-
方法安全性:使用
@PreAuthorize
、@PostAuthorize
、@Secured
等注解在方法上定义安全性。 -
URL安全性:使用Spring Security的配置类或XML配置定义URL访问权限。
使用Java配置方式
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll() // 公开访问的URL
.anyRequest().authenticated() // 其他所有请求需要认证
.and()
.formLogin() // 启用表单登录
.loginPage("/login") // 自定义登录页面路径
.permitAll() // 登录页面可公开访问
.and()
.logout() // 启用注销功能
.permitAll(); // 注销功能可公开访问;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication() // 使用内存中的用户存储
.withUser("user").password(passwordEncoder().encode("password")).roles("USER"); // 定义用户和角色
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 使用BCrypt加密密码
}
}