首页 > 解决方案 > Spring Web Security 问题中的身份验证

问题描述

我将通过实现的自定义类设置后台 Spring 身份验证UserDetailsService。正如文档方法中loadUserByUsername所说,每次用户尝试登录时都会调用,但在下面的情况下不会。

@Component
public class AuthenticationUserDetailsService implements UserDetailsService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<Person> personByUserName = personRepository.findPersonByUserName(username);

        Person person = personByUserName.
                orElseThrow(() -> new UsernameNotFoundException("User with username has not found"));

        return new User(username, person.getPassword(), Collections.emptyList());
    }

}

我尝试使用几种替代方法在 WebSecurityConfig 类中设置 configure(HttpSecurity http) 方法。

  1. @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable();

        http
                .authorizeRequests()
                .anyRequest().authenticated() 
    
                .and()
                .formLogin()
                .loginProcessingUrl("api/person/login") 
                .usernameParameter("username")
                .passwordParameter("password");
    }
    
  2. @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable();

        http
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers("/index.html", "/", "/home", "/api/person/login").permitAll()
                .anyRequest().authenticated();
    
    }
    
  3. @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable();

                http.
                authorizeRequests().
                anyRequest().authenticated()
               .and().
                formLogin().
                loginProcessingUrl("/login").
                usernameParameter("username").
                passwordParameter("password");
    

    }

注册 DaoAuthenticationProvider:

  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(getAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider getAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(authenticationUserDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }

谁能解释一下,错误在哪里,为什么loadUserByUsername方法根本不调用?

Angular 8 UI 部分用于登录。

public loginPerson(person: Person): Observable<Person> {
    let url = "http://localhost:8080/login";
    return this.httpClient.post<Person>(url, {userName: person.username, password: person.password});
  }

标签: springspring-security

解决方案


推荐阅读