当前位置: 首页 > 知识库问答 >
问题:

使用return getAuthenticationManager()返回错误凭据。验证()

松雅健
2023-03-14

我是Spring Security的新手,我做了以下教程:https://windoctor7.github.io/spring-jwt.html

但是我修改了一些数据库中搜索用户的代码,所以,我创建了一个@bean:

1部分,拦截呼叫。

@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());
    }

}

用户是正确的,最后一行:

return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),
                        user.getPassword(), grantedAuths));

我在AbstractAuthenticationProcessingFilter中遇到错误。类

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。安全认证。BadCredentialsException:糟糕的凭证我不明白,什么凭证???我的用户是正确的,存在于数据库中,为什么我会出错???我只修改el@bean,因为我可以使用@autowired。。。谢谢

用Saad Surya的答案修改:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "es.....service")
public class ServiciosConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceImpl userDetailService;

    @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;
    }

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

因此,我删除了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.") {
            };
        }
    }

}

在这里,我的类检查存储库中的用户并创建MyUserMain()

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;
    }

}

具有UserDetails的类实现。由于我将的isEnabled、IsCredentials NonExpired、isAccountNonLocked、isAccountNonExpired修改为true,所以出现了提示。

Okkk,有了这些,我启动了我的应用程序,但我得到了同样的错误:“身份验证失败:错误的凭据”,

不同的是现在我得到了课堂上的错误

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);
            }

共有1个答案

章稳
2023-03-14

您可以通过覆盖configure(AuthenticationManagerBuilder)websecurityConfigureAdapter的method来实现UserDetailsService并配置它,而不是为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
    }

}
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userDetailService;

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

 类似资料:
  • 因为我正在尝试使用spring Boot在oauth2实现中创建简单的登录。不幸的是它不起作用,因为我是spring我的配置的新手 ApplicationStarter.java ResourceServerConfiguration.java OAuth2SecurityConfiguration.java 请纠正我哪里错了?是否需要更多的配置? 正如我跟随http://websystique.

  • 问题内容: 这是一个非常简单的测试,但我似乎无法正确完成。 我想检查哪些用户可以登录并执行操作(这是一整套测试的一部分),但是第一步会引起一些问题。 当我运行测试时,我得到: 为什么我不正确登录时django返回HTTP代码? 对于其他上下文,这是我如何管理登录/注销URL: 问题答案: Web社区中有一些关于对凭证失败的正确响应的辩论。例如,这是有关从切换到的Wordpress凭单。在Stack

  • 在此处为客户端凭据流使用Spotify文档: 我能够在谷歌应用程序脚本(Javascript)中创建API请求。 我对两件事感到困惑,请能够回答这两件事。 1). Spotify文档声明在授权标头中的客户端凭据之前输入“Basic”。 然而,当我运行这段代码时,我得到了这个错误 如果我在使用客户端凭据流,为什么它认为我在使用承载令牌?(同样,如果我将身份验证更改为Bearer,我会收到401错误“

  • 我在Vue后端使用Laravel 6 passport grant密码。 当我发送正确的凭据到oauth/令牌它的工作和返回令牌,但当我发送错误(电子邮件/密码)它返回400而不是401与此消息。 我检查了客户id和客户机密。 我使用新安装的Laravel passport进行测试,没有一行代码,Laravel 5.8返回401,没有任何问题,但Laravel 6返回400个错误请求。 你知道吗?

  • Facebook登录没问题,但Firebase无法获取Facebook帐户详细信息。 我已经检查了firebase网站中无效的_凭据意味着什么 一旦我构建,它就会显示: 登录了 登录失败。Error Domain=FirebaseAuthentication Code=-11“(错误代码:INVALID_凭据)提供的验证凭据无效。”UserInfo={details={“providerError

  • 我正在尝试使用grails-sporing-security-rest和grails-spring-security-ldap插件实现REST API的安全性。 流程应该是这样的,一旦实现了身份验证提供者,它将使用身份验证机制对用户进行身份验证。 但在我的情况下,我正在尝试验证JSON用户名和密码POST请求,下面是输出。 如果您观察日志,SpringSecurityLDAPTemboard身份验