有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在应用程序中使用身份验证设置时获得401响应

我已经创建了一个服务,它可以将一个新用户保存到数据库中,并(应该)对用户进行身份验证。 我现在遇到的问题是,在使用该服务创建之后,我无法使用相同的用户名和密码对我的用户进行身份验证

身份验证:基本身份验证
密码编码器:BCryptPasswordEncoder
数据库:本地Mongodb

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private PasswordEncoder encoder;

@Autowired
private UserService userService;

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests().antMatchers("/config", "/registerUser").permitAll()
            .and()
            .authorizeRequests().antMatchers("/**").authenticated().and().httpBasic()
            .and().logout().logoutSuccessUrl("/").permitAll()


    ;
}

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
//authentication will work if I switch to the in-memory authentication below
//        authManagerBuilder
//                .inMemoryAuthentication()
//                .withUser("user").password(encoder.encode("password")).roles("USER");

    authManagerBuilder.authenticationProvider(authProvider());
}

@Bean
public DaoAuthenticationProvider authProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userService);
    authProvider.setPasswordEncoder(this.encoder);
    return authProvider;
}

}



@Service
public class UserService implements IUserService {

    @Autowired
    private UserDetailRepository userDetailRepository;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public User saveUser(User user) {
        String password = user.getPassword();
        String passwordHased = this.encoder.encode(password);
        user.setPassword(passwordHased);
        User ud = this.userDetailRepository.save(user);
        return ud;
    }

    @Override
    public User getUserWithId(String userId) {
        return this.userDetailRepository.findById(userId).get();
    }

    @Override
    public User loadUserByUsername(String s) throws UsernameNotFoundException {
        return this.userDetailRepository.findByUsername(s);
    }
}



public class User implements UserDetails {
    @Id
    private String userId;

    private String username;

    private String password;


    @Override
    public final Collection<? extends GrantedAuthority> getAuthorities() {
        List<String> privileges = new ArrayList<>();
        privileges.add("READ");
        privileges.add("WRITE");
        return getGrantedAuthorities(privileges);
    }
    private final List<GrantedAuthority> getGrantedAuthorities(final List<String> privileges) {
        final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (final String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }


... (other overridden methods omitted)

}

我怀疑我的getAuthories()方法没有正确执行。
如果你需要更多信息,请告诉我


共 (1) 个答案

  1. # 1 楼答案

    我在回答我自己的问题

    我上面发布的代码没有什么问题,只是我遗漏了发布的内容。在扩展UserDetails的用户类中,有几个方法需要重写

      @Override
        public boolean isAccountNonExpired() {
            return true;
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
    
        @Override
        public boolean isEnabled() {
            return true;
        }
    

    它们现在都设置为返回true,并且有效,以前它们都返回false

    愚蠢的错误