spring引导+安全加载用户名未传递用户名

aemubtdh  于 2021-09-30  发布在  Java
关注(0)|答案(2)|浏览(349)

我使用SpringSecurity+SpringJWT+SpringJPA对用户进行身份验证。我有一个rest端点/身份验证,它通过身份验证管理器对用户进行身份验证。spring security createauthenticationtoken()调用loadbyusername(字符串用户名)。但是,当我调试它的打印时,没有人可以看到下面的代码

@SpringBootApplication
 @EnableJpaRepositories(basePackageClasses=UsersRepo.class)
 @ComponentScan(basePackages = {"com.test.ws"})

 public class TestWebApp{

 public static void main(String[] args) {
    SpringApplication.run(TestWebApp.class, args);
 }
}

控制器类

@RestController
public class HelloResource {
@Autowired
AuthenticationManager authenticationManager;

@Autowired
UserDeatilService userDeatilService;

@Autowired
JwtUtils jwtUtils;

@RequestMapping(value="/authenticate",method=RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody Users authenticationRequest) throws Exception{

authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));

    final UserDetails userDetails=userDeatilService.loadUserByUsername(authenticationRequest.getUsername());

    final String jwt=jwtUtils.generateToken(userDetails);

    return ResponseEntity.ok(new AuthenticationResponse(jwt));

}

服务等级

@Service
 public class UserDeatilService implements UserDetailsService{

@Autowired
UsersRepo userRepo;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    System.out.println("inside loadUserByUsername::"+username);

    Optional<Users> user=userRepo.findByUserName(username); 

    user.orElseThrow(()->new UsernameNotFoundException("Not found: "+username));

    return user.map(MyUserDetail::new).get();
   }
 }

证券配置师

@EnableWebSecurity
public class Securityconfigurer extends WebSecurityConfigurerAdapter {

@Autowired
private UserDeatilService  userDeatilService;

/*@Autowired
private JwtRequestFilter jwtRequestFilter;*/

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDeatilService);
}

//Dont manage session
@Override
protected void configure(HttpSecurity http) throws Exception{
     //http.csrf().disable().authorizeRequests().antMatchers("/h2-console/**").hasAnyRole("h2").antMatchers("/authenticate").permitAll().anyRequest().authenticated();
    /*.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);*/

    http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN").antMatchers("/authenticate").hasAnyRole("ADMIN","USER").antMatchers("/").permitAll().and().formLogin();

}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    // TODO Auto-generated method stub
    return super.authenticationManagerBean();
}

存储库

@Repository
  public interface UsersRepo extends JpaRepository<Users,Integer>{
     Optional<Users> findByUserName(String username);
  }

Myuesr详细信息

public class MyUserDetail implements UserDetails{

private String username;
private String password;
private boolean active;
private List<GrantedAuthority> authorities;

public MyUserDetail(Users user) {
    this.username=user.getUsername();
    this.password=user.getPassword();
    this.active=user.isActive();
    this.authorities=Arrays.stream(user.getRoles().split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}

public MyUserDetail() {
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    // TODO Auto-generated method stub
    return authorities;
}

@Override
public String getPassword() {
    // TODO Auto-generated method stub
    return password;
}

@Override
public String getUsername() {
    // TODO Auto-generated method stub
    return username;
}

@Override
public boolean isAccountNonExpired() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isAccountNonLocked() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isEnabled() {
    // TODO Auto-generated method stub
    return active;
}}
pb3skfrl

pb3skfrl1#

例外情况是:
“找不到类型用户的属性用户名!你是说“用户名”吗。
在您的存储库中,您声明了一个名为findbyusername的函数,并且应该是findbyusername,因为您将MyUserDeDetails的这个属性定义为username而不是username,它区分大小写。

34gzjxbg

34gzjxbg2#

看起来您的异常中显示了所有内容:
通过字段“userdeatilservice”表示的未满足的依赖关系;
嵌套异常为org.springframework.beans.factory.unsatifiedpendencyException:创建名为“userdeatilservice”的bean时出错:通过字段“userrepo”表示未满足的依赖关系;
嵌套异常为org.springframework.beans.factory.beancreationexception:创建名为“usersrepo”的bean时出错,该bean在com.barsamin.ws.repo.usersrepo中定义,在barsaminwebapplication上声明的@enablejparepositories中定义:
调用init方法失败;嵌套异常为java.lang.illegalargumentexception:
无法为方法public abstract java.util.optional com.barsamin.ws.repo.usersrepo.findbyusername(java.lang.string)创建查询!
找不到类型用户的属性用户名!你是说“用户名”吗?

相关问题