Java 使用return getAuthenticationManager()返回错误的凭据。authenticate()
我是Spring Security的新手,我完成了以下教程: 但我对数据库中搜索用户的代码做了一些修改,因此,我创建了一个@bean: 1º部分,拦截呼叫Java 使用return getAuthenticationManager()返回错误的凭据。authenticate(),java,spring,spring-security,Java,Spring,Spring Security,我是Spring Security的新手,我完成了以下教程: 但我对数据库中搜索用户的代码做了一些修改,因此,我创建了一个@bean: 1º部分,拦截呼叫 @Configuration @EnableWebSecurity @ComponentScan(basePackages = "es.....service") public class ServiciosConfig extends WebSecurityConfigurerAdapter { @Bean public
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "es.....service")
public class ServiciosConfig extends WebSecurityConfigurerAdapter {
@Bean
public LoginFilter createLogin() throws Exception {
return new LoginFilter("/login", authenticationManager());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/login").permitAll() //permitimos el acceso a /login a cualquiera
.anyRequest().authenticated() //cualquier otra peticion requiere autenticacion
.and()
// Las peticiones /login pasaran previamente por este filtro
.addFilterBefore(createLogin(), UsernamePasswordAuthenticationFilter.class)
// Las demás peticiones pasarán por este filtro para validar el token
.addFilterBefore(new JwtFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
我截取“登录”并在数据库中搜索(如果用户存在):
public class LoginFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);
@Autowired
private RolesUserRepository rolRepository;
@Value("${ldap.base}")
private String base;
public LoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
// obtenemos el body de la peticion que asumimos viene en formato JSON
InputStream body = req.getInputStream();
// Realizamos un mapeo a nuestra clase User para tener ahi los datos
User user = new ObjectMapper().readValue(body, User.class);
// Finalmente autenticamos
LOGGER.info("Buscando al usuario: " + user.getUsername() + " en la BD.");
RolesUser rol = this.rolRepository.findByUser(user.getUsername());
if (rol.getRol() != null) {
LOGGER.info("El usuario: " + user.getUsername() + " es correcto.");
List<GrantedAuthority> grantedAuths = AuthorityUtils.commaSeparatedStringToAuthorityList(rol.getRol());
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(), grantedAuths));
} else {
throw new javax.security.sasl.AuthenticationException("Credenciales inválidas.");
}
}
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
// Si la autenticacion fue exitosa, agregamos el token a la respuesta
JwtUtil.addAuthentication(res, auth.getName());
}
我在AbstractAuthenticationProcessingFilter.class中遇到错误
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!requiresAuthentication(request, response)) {
chain.doFilter(request, response);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
Authentication authResult;
try {
authResult = attemptAuthentication(request, response);
if (authResult == null) {
// return immediately as subclass has indicated that it hasn't completed
// authentication
return;
}
sessionStrategy.onAuthentication(authResult, request, response);
}
catch (InternalAuthenticationServiceException failed) {
logger.error(
"An internal error occurred while trying to authenticate the user.",
failed);
unsuccessfulAuthentication(request, response, failed);
return;
}
catch (AuthenticationException failed) {
// Authentication failed
unsuccessfulAuthentication(request, response, failed);
return;
}
// Authentication success
if (continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
successfulAuthentication(request, response, chain, authResult);
}
在中,身份验证未成功(请求、响应、失败)代码>
代码错误为org.springframework.security.authentication.BadCredentialsException:错误凭据
我不明白,什么证件???我的用户是正确的,存在于数据库中,为什么我会出错???我只修改el@bean,因为我可以使用@autowired。。。谢谢
修改答案Saad Surya:
因此,我删除了LoginFilter的逻辑:
public class LoginFilter extends AbstractAuthenticationProcessingFilter {
public LoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
// obtenemos el body de la peticion que asumimos viene en formato JSON
InputStream body = req.getInputStream();
// Realizamos un mapeo a nuestra clase User para tener ahi los datos
User user = new ObjectMapper().readValue(body, User.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
user.getUser(),
user.getPwd(),
Collections.emptyList()
)
);
}
现在我直接返回getAuthenticationManager
我使用userDetailsService接口来检查凭证,并返回一个obj userDetails,其中包含el user和rol,用于创建令牌jwt
@Service
public class UserServiceImpl implements UserDetailsService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private RolesUserRepository repository;
public void UserService(RolesUserRepository repository) {
this.repository = repository;
}
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
RolesUser rolUser = repository.findByUser(userName);
if(rolUser.getRol() != null) {
LOGGER.info("El usuario: " + userName + " es: " + rolUser.getRol());
List<GrantedAuthority> grantedAuths = AuthorityUtils.commaSeparatedStringToAuthorityList(rolUser.getRol());
return new MyUserPrincipal(grantedAuths,"",userName);
}else {
throw new AuthenticationException("Las credenciales son incorrectas.") {
};
}
}
}
您可以实现UserDetailsService
并通过覆盖configure(AuthenticationManagerBuilder)
的WebSecurityConfigureAdapter
方法对其进行配置,而不是为LoginFilter
创建bean
public class UserService implements UserDetailsService {
private UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
@Override
public UserDetails loadUserByUsername(String username) {
// you call to repository to get user
}
}
最后我用字符串password=“123”解决了这个问题;PasswordEncoder PasswordEncoder=(PasswordEncoder)新的BCryptPasswordEncoder();字符串encodedPassword=((BCryptPasswordEncoder)passwordEncoder).encode(密码);返回新的MyUserPrincipal(grantedAuths、encodedPassword、用户名);现在我需要解决如何获得密码。谢谢
@Service
public class UserServiceImpl implements UserDetailsService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private RolesUserRepository repository;
public void UserService(RolesUserRepository repository) {
this.repository = repository;
}
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
RolesUser rolUser = repository.findByUser(userName);
if(rolUser.getRol() != null) {
LOGGER.info("El usuario: " + userName + " es: " + rolUser.getRol());
List<GrantedAuthority> grantedAuths = AuthorityUtils.commaSeparatedStringToAuthorityList(rolUser.getRol());
return new MyUserPrincipal(grantedAuths,"",userName);
}else {
throw new AuthenticationException("Las credenciales son incorrectas.") {
};
}
}
}
public class MyUserPrincipal implements UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<GrantedAuthority> grantedAuths;
private String password;
private String userName;
public MyUserPrincipal(List<GrantedAuthority> grantedAuths, String password, String userName) {
this.grantedAuths = grantedAuths;
this.password = password;
this.userName = userName;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.grantedAuths;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.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 true;
}
}
AbstractUserDetailsAuthenticationProvider, Line 171.
catch (AuthenticationException exception) {
if (cacheWasUsed) {
// There was a problem, so try again after checking
// we're using latest data (i.e. not from the cache)
cacheWasUsed = false;
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
}
public class UserService implements UserDetailsService {
private UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
@Override
public UserDetails loadUserByUsername(String username) {
// you call to repository to get user
}
}
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userDetailService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailService);
}
}