spring - 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) 方法。
@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"); }
@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(); }
@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});
}
解决方案
推荐阅读
- r - R包“羽毛”给我错误“check_dots_empty中的错误(动作=信号):未使用的参数(动作=信号)”
- javascript - firebase - 用户首次注册后再次登录
- bash - 为 ecs update-service 运行 aws cli 时,分配给变量时出现错误
- elasticsearch - Micrometer ElasticSearch 将 JSON 名称转换为 Key
- python - 在 Python 中执行跨列计算
- python - Python:如何修复 Python 中的 AttributeError?
- asp.net-core - 使用 Kestrel 和 IdentityServer4 在 LAN 中托管 ASP.NET CORE 5
- python - 在 GPU 上使用 keras 进行集成预测
- r - 错误(函数(...,row.names = NULL,check.rows = FALSE,check.names = TRUE,:参数暗示不同的行数:1、3、4
- r - 基于 x 轴标签的颜色