在Spring Security中,我不了解身份验证的工作方式。在文档中,他们有此代码
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") 1
.permitAll(); 2
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
上面,.anyRequest().authenticated()
是如何工作的?在春季,它会自动验证用户身份吗?
这行.anyRequest().authenticated()
调用configureGlobal
并使用用户名和密码进行身份验证吗?通常用户名和密码保存在数据库中吗?然后如何检查用户名和密码保存在用户表中的用户的身份验证?
在上面,.anyRequest()。authenticated()如何工作?在春季,它会自动验证用户身份吗?
HttpSecurity
创建一个安全筛选器链,并且将通过应用于HttpSecurity
的配置程序添加该链中的筛选器。当你做
http
.authorizeRequests()
.anyRequest().authenticated()
…
您正在添加将用于创建ExpressionUrlAuthorizationConfigurer
的FilterSecurityInterceptor
,这是一个过滤器,它将决定当前用户是否满足获取对资源的访问的要求。对于您的情况,FilterSecurityInterceptor
将确保针对每个请求对用户进行身份验证(而不使用AnonymousAuthenticationToken
)。
FilterSecurityInterceptor
的主要工作不是身份验证。它期望Authentication
已经在SecurityContextHolder中。否则会引发异常。
就像这行.anyRequest()。authenticated()调用configureGlobal并使用用户名和密码进行身份验证吗?通常用户名和密码保存在数据库中吗?然后如何检查用户名和密码保存在用户表中的用户的身份验证?
验证实际上在这里进行:
.formLogin()
.loginPage("/login") 1
.permitAll();
FormLoginConfigurer
将UsernamePasswordAuthenticationFilter
添加到链,默认情况下将响应“ / login”。旁注:如果查看WebSecurityConfigurerAdapter
(通常从该类开始扩展以获得一些合理的默认值),则会看到默认情况下某些配置程序和过滤器将应用于HttpSecurity。
AuthenticationManagerBuilder
中的@Autowired
将用于创建AuthenticationManager
,然后与包括UsernamePasswordAuthenticationFilter
的多个过滤器共享以进行认证。过滤器从"username"
中提取"password"
和HttpServletRequest
参数,将它们存储在UsernamePasswordAuthenticationToken
中,然后将其传递给AuthenticationManager
。
代替
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
您可以尝试:
auth
.jbdcAuthentication()
.dataSource(dataSource)
//.other methods to configure UserDetailsService default
;
查看JdbcUserDetailsManager
(它是默认的JdbcUserDetailsManager
),以查看执行了哪些SQL命令以及在身份验证时期望在UserDetailsService
表中找到哪些行名。