我一直在为我的应用程序中的身份验证而苦苦挣扎,对于一些不为人知的原因,它不能正常运行。我确信我传递了正确的用户名和密码,但仍然无法通过应用程序正确地进行身份验证。
这是安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(passwordEncoder());
authenticationProvider.setUserDetailsService(userDetailsService);
return authenticationProvider;
}
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
//auth.inMemoryAuthentication().withUser("admin1").password("admin").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/account").hasRole("USER")
.and().formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout")
.and().exceptionHandling().accessDeniedPage("/403")
.and().csrf().disable();
}
}
用户服务:
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService extends MainService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
private static final Logger LOGGER = Logger.getLogger(UserService.class);
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
LOGGER.debug("Attempt to log in user with given username: " + login);
User user = userRepository.findByAccountLogin(login);
if(user == null) {
throw new UsernameNotFoundException("User with login: " + login + " does not exist");
}
LOGGER.debug("Loaded account: " + user.getAccount() + " password matches: " + new BCryptPasswordEncoder().matches("admin", user.getAccount().getPassword()));
return new org.springframework.security.core.userdetails.User(user.getAccount().getLogin(), user.getAccount().getPassword(), user.getAccount().getActivated(), true, true, true, getGrantedAuthorities(user));
}
private List<GrantedAuthority> getGrantedAuthorities(final User user) {
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for(AccountRole role : user.getAccount().getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getId().getaRole().getType()));
}
LOGGER.debug("Granted authorities: " + grantedAuthorities);
return grantedAuthorities;
}
}
这段代码确保我已经传递了正确的数据:
LOGGER.debug("Loaded account: " + user.getAccount() + " password matches: " + new BCryptPasswordEncoder().matches("admin", user.getAccount().getPassword()));
原因可能是什么?