如何使用AuthenticationManagerBuilder和userDetailsS​​ervice基于从用户实体重新获取的凭据在Spring中对用户进行身份验证

时间:2017-10-28 08:58:42

标签: java spring

我是春天的新手 无法实现登录到应用程序,实际上无法弄清楚它的错误。 跟着youtube视频来做这一切。 非常感谢帮助。 当我尝试登录该应用程序时,不允许登录。 控制台日志显示正在执行查询但无法登录系统。 密码也以纯ASCII格式保存。

WebSecurityConfig类

@Configuration
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AccessDeniedHandler accessDeniedHandler;

@Autowired 
private UserDetailsService userDetailsService;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsService);
} 


// roles admin allow to access /actuator/**
// roles user allow to access /Application/**
// custom 403 access denied handler

@Override
protected void configure(HttpSecurity http) throws Exception {
    // some antMatchers permit all
}
}

customUserDetailsS​​ervice类

@Service("customUserDetailsService")
public class CustomUserDetailsService  implements UserDetailsService{

private final UserRepo userRepo;

@Autowired
public CustomUserDetailsService(UserRepo userRepo) {
    this.userRepo = userRepo;
}

@Override
// userId is reffered as username
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    User user=userRepo.findByUsername(userName);
    if(null == user){
        System.out.println("\n\n\n No user present with username: "+userName);
        throw new UsernameNotFoundException("No user present with username: "+userName);
    }else{  

        CustomUserDetails c =new CustomUserDetails(user);
        //System.out.println(c.getAuthorities());
        return c;
    }
}


}

CustomUserDetails类

public class CustomUserDetails extends User implements UserDetails{

private static final long serialVersionUID = 1L;

public CustomUserDetails(User user){
    super(user);

}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {

    Collection<UserRole> roles = super.getUserRole();
    List<String> userRoles= new ArrayList<String>();

    for(UserRole r : roles) {
        userRoles.add(r.getRole().toString());
    }

    String strRoles=StringUtils.collectionToCommaDelimitedString(userRoles);
    return AuthorityUtils.commaSeparatedStringToAuthorityList(strRoles);
}

@Override
public boolean isAccountNonExpired() {
    return super.isAccountNonExpired();
}

@Override
public boolean isAccountNonLocked() {
    return super.isAccountNonLocked();
}

@Override
public boolean isCredentialsNonExpired() {
    return super.isCredentialsNonExpired();
}

@Override
public boolean isEnabled() {
    return super.isEnabled();
}

@Override
public String getUsername() {
    return super.getUsername();
}

@Override
public String getPassword() {
    return super.getPassword();
}

}

0 个答案:

没有答案