【发布时间】:2021-02-15 10:25:42
【问题描述】:
我正在开发启用了 Spring Security 的 Spring Boot 应用程序。我正在使用自定义 jdbc 身份验证。在我的用户详细信息服务中,我抛出了 usernamenotfound 异常,但它没有在任何地方记录。我也没有在控制台上看到任何内容。
下面是我的 UserDetailService 实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class ApplicationUserDetailService implements UserDetailsService{
private ApplicationUserDao applicationUserDao;
@Autowired
public ApplicationUserDetailService(@Qualifier("db") ApplicationUserDao applicationUserDao) {
this.applicationUserDao=applicationUserDao;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return applicationUserDao.loadUserByUsername(username)
.orElseThrow(()->{
System.out.println("here...");
throw new UsernameNotFoundException("dsdsds");
});
}
}
下面是jdbc auth的安全配置
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(provider());
}
@Bean
public DaoAuthenticationProvider provider() {
DaoAuthenticationProvider pr=new DaoAuthenticationProvider();
pr.setUserDetailsService(applicationUserDetailService);
pr.setPasswordEncoder(encoder);
return pr;
}
UserDetailDaoImpl
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
@Repository("db")
public class DBUserDaoImpl implements ApplicationUserDao{
private final JdbcTemplate jdbcTemplate;
@Autowired
public DBUserDaoImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate=jdbcTemplate;
}
@Override
public Optional<ApplicationUser> loadUserByUsername(String username) throws UsernameNotFoundException {
return Optional.ofNullable(jdbcTemplate.query("select * from users where username='"+username+"'"
,new UserExtractor(jdbcTemplate)));
}
}
当我发送错误的详细信息时,我应该得到异常,但它没有出现。请帮帮我。Spring boot 2.4.2
【问题讨论】:
-
i should get exception but it is not coming那么接下来会发生什么?应使用当前行为和调试日志更新问题。 -
嗨@Toerktumlare,我在控制台中什么也没有。仅完成调度程序 servlet 请求。日志---- Initializing Spring DispatcherServlet 'dispatcherServlet' o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' o.s.web.servlet.DispatcherServlet : 0 ms内完成初始化
-
请发布您的完整调试服务器日志。
-
1.您的查询很危险,2.为什么
UserExtractor中的模板? 3.UserExtractor具体是做什么的? -
UserExtractor 将结果集的结果映射到 UserDetails 类 impl。传递 jdbc 模板是因为在用户提取器中,如果我们找到了用户,那么我将获取用户的角色,然后构建应用程序用户以进行身份验证。
标签: spring spring-boot spring-security