Java 为什么不是';我的Spring Boot api是否使用正确的用户名/密码验证MySQL数据库中的用户?
我是spring boot的新手,我正在制作一个用于练习的web应用程序。我正在尝试为我的Spring Boot项目设置身份验证。我在学习一个教程,他们提到在Java 为什么不是';我的Spring Boot api是否使用正确的用户名/密码验证MySQL数据库中的用户?,java,spring-boot,spring-security,Java,Spring Boot,Spring Security,我是spring boot的新手,我正在制作一个用于练习的web应用程序。我正在尝试为我的Spring Boot项目设置身份验证。我在学习一个教程,他们提到在UserDetailsService(我的实现)中,我应该自动连接返回现有用户的JPA存储库。用户名匹配。一旦UserDetails对象被传递回AuthenticationProvider,我就用调试器逐行跟踪程序的流程,它似乎遇到了“InvocationTargetException”,然而,我的控制台stacktrace上没有显示任何内
UserDetailsService
(我的实现)中,我应该自动连接返回现有用户的JPA存储库。用户名匹配。一旦UserDetails对象被传递回AuthenticationProvider,我就用调试器逐行跟踪程序的流程,它似乎遇到了“InvocationTargetException”,然而,我的控制台stacktrace上没有显示任何内容。
我可能做错了什么
另一个问题是,应该在哪里验证密码?authenticationmanager
是否在内部处理该问题
身份验证控制器:
@RestController
@RequestMapping("api/auth")
public class Auth {
@Autowired
private AuthService authService;
@PostMapping("login")
public AuthenticationResponse login(@RequestBody LoginRequest loginRequest) {
System.out.println("part 1");
return authService.login(loginRequest);
}
授权服务:
@AllArgsConstructor
@Service
public class AuthService {
private final PasswordEncoder passwordEncoder;
private final HunterRepository hunterRepo;
private final AuthenticationManager authenticationManager;
public AuthenticationResponse login(LoginRequest loginRequest) {
org.springframework.security.core.Authentication authenticate =
authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
loginRequest.getPassword()));
System.out.println("check 2: " + authenticate.isAuthenticated());
SecurityContextHolder.getContext().setAuthentication(authenticate);
String token = jwtProvider.generateToken(authenticate);
System.out.println("this is token: " + token);
return new AuthenticationResponse(token, loginRequest.getUsername());
}
SecurityConfig:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
public SecurityConfig(UserDetailsServiceImpl userDetailsService){
this.userDetailsService = userDetailsService;
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/**")
.permitAll()
.antMatchers("/api/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/posts/")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/posts/**")
.permitAll()
// change the bottom matchers to my site's urls
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**")
.permitAll()
.anyRequest()
.authenticated();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationManager) throws Exception
{
authenticationManager.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
PasswordEncoder passwordEncoder() {
/*
* passwordEncoder is part of spring security. it is used to encrypt passwords with a
* BCrypt hashing algorithm
*/
return new BCryptPasswordEncoder();
}
}
UserDetailsServiceImpl
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final HunterRepository hunterRepo;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("check 2: " + username);
Optional<Hunter> userOptional = hunterRepo.findByUsername(username);
System.out.println("check 3, is value present?" + userOptional.isPresent());
// Hunter hunter = userOptional
// .orElseThrow(() -> new UsernameNotFoundException("No user " +
// "Found with username : " + username));
Hunter hunter = null;
if (userOptional.isPresent())
{
System.out.println("userOptional is present");
hunter = userOptional.get();
}
else
{
System.out.println("userOptional is not present");
throw new UsernameNotFoundException("no user found with username");
}
return new org.springframework.security
.core.userdetails.User(hunter.getUsername(), hunter.getPassword(),
hunter.isEnabled(), true, true,
true, getAuthorities("USER"));
}
private Collection<? extends GrantedAuthority> getAuthorities(String role) {
//return Collections.singletonList(new SimpleGrantedAuthority(role));
return Arrays.asList(new SimpleGrantedAuthority(role));
}
}
@服务
@AllArgsConstructor
公共类UserDetailsServiceImpl实现UserDetailsService{
私人最终亨特雷波公寓;
@凌驾
@交易的
public UserDetails loadUserByUsername(字符串用户名)引发UsernameNotFoundException{
System.out.println(“检查2:+用户名);
可选userOptional=hunterRepo.findByUsername(用户名);
System.out.println(“检查3,值是否存在?”+userOptional.isPresent());
//Hunter=userOptional
//.orelsetrow(()->新用户名NotFoundException(“无用户”)+
//使用用户名找到:“+username”);
Hunter=null;
if(userOptional.isPresent())
{
System.out.println(“存在用户可选”);
hunter=userOptional.get();
}
其他的
{
System.out.println(“userOptional不存在”);
抛出新的UsernameNotFoundException(“找不到用户名为的用户”);
}
返回新的org.springframework.security
.core.userdetails.User(hunter.getUsername(),hunter.getPassword(),
hunter.isEnabled(),真的,真的,
正确,GetAuthories(“用户”);
}
private Collection能否显示InvocationTargetException
的堆栈跟踪?尤其是由节引起的最后一个。@dan1st堆栈跟踪没有抛出任何错误。我应该显示什么?如果调试器显示它,请在出现它的位置添加一个try-catch并执行e.printStackTrace()
。
public interface HunterRepository extends CrudRepository<Hunter, Integer>{
Optional<Hunter> findByUsername(String username);
}