了解Spring安全认证

问题描述 投票:2回答:1

在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并使用用户名和密码进行身份验证吗?通常用户名和密码保存在数据库中吗?然后如何检查用户名和密码保存在用户表中的用户的身份验证?

spring authentication spring-security authorization
1个回答
0
投票

在上面,.anyRequest()。authenticated()如何工作?在春季,它会自动验证用户身份吗?

HttpSecurity创建一个安全筛选器链,并且将通过应用于HttpSecurity的配置程序添加该链中的筛选器。当你做

http
    .authorizeRequests()
        .anyRequest().authenticated()
    …

您正在添加将用于创建ExpressionUrlAuthorizationConfigurerFilterSecurityInterceptor,这是一个过滤器,它将决定当前用户是否满足获取对资源的访问的要求。对于您的情况,FilterSecurityInterceptor将确保针对每个请求对用户进行身份验证(而不使用AnonymousAuthenticationToken)。

FilterSecurityInterceptor的主要工作不是身份验证。它期望Authentication已经在SecurityContextHolder中。否则会引发异常。

就像这行.anyRequest()。authenticated()调用configureGlobal并使用用户名和密码进行身份验证吗?通常用户名和密码保存在数据库中吗?然后如何检查用户名和密码保存在用户表中的用户的身份验证?

验证实际上在这里进行:

.formLogin()
    .loginPage("/login") 1
    .permitAll(); 

FormLoginConfigurerUsernamePasswordAuthenticationFilter添加到链,默认情况下将响应“ / 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表中找到哪些行名。

© www.soinside.com 2019 - 2024. All rights reserved.