使用自定义数据源和Spring Security密码编码器,但登录失败。
Sping Boot 版本2.7.0
我先注册了一个名为“132456”的用户,口令为“123456”,然后登录,但是失败了;
然后创建一个测试类:打印真实
@Test
public void selectTest() {
UserDetails userDetails = userInfoService.loadUserByUsername("123456");
System.out.println(userDetails);
boolean matches = passwordEncoder.matches("123456", userDetails.getPassword());
System.out.println(matches);
}
字符串
Spring Security配置
@EnableWebSecurity
@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration {
@Autowired
UserInfoService userInfoService;
@Autowired
Gson gson;
@Autowired
JwtTokenFilter jwtTokenFilter;
@Autowired
PasswordEncoder passwordEncoder;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
.... login url has pass
http.formLogin().loginProcessingUrl("/api/login").permitAll()
.successHandler((request, response, authentication) -> {
this.sendMessage(response, authentication);
})
.failureHandler((request, response, exception) ->
jwtTokenFilter.sendError(response, HttpServletResponse.SC_UNAUTHORIZED, "username or password error"));
http.logout().invalidateHttpSession(true).clearAuthentication(false);
http.rememberMe().disable();
http.csrf().disable();
return http.build();
}
@Bean
DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userInfoService);
authProvider.setPasswordEncoder(passwordEncoder);
return authProvider;
}
}
型
userServiceImpl
// use mybatisplus framework
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(UserInfo::getUsername, username);
return getOne(queryWrapper);
}
@Override
public boolean create(UserInfoDTO userInfoDTO) {
userInfoDTO.setPassword(passwordEncoder.encode(userInfoDTO.getPassword()));
return save(BeanUtil.copyProperties(userInfoDTO, UserInfo.class));
}
}
型
登录成功,然后返回令牌。
1条答案
按热度按时间46scxncf1#
天哪,我忘了覆盖接口
UserDetails
的内部方法:isEnabled()
,哈哈哈。花了两个小时才找到这个bug。字符串