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

W.A.UsernamePasswordAuthenticationFilter:尝试对用户进行身份验证时出现内部错误

寇照
2023-03-14

我无法登录我的系统。当我在我的web表单中插入数据并点击登录按钮时,我的系统不工作。(数据是正确的)。

用户实体:

    @Entity
    @Table(name = "usr_usuarios")
    public class Usuario {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "usr_id")
        private Long id;

        @Column(name = "usr_email", nullable = false, length = 100)
        @NotNull(message = "O email é obrigatório")
        @Length(min = 5, max = 100, message = "O email deve conter entre 5 e 100 caracteres.")
        private String email;

        @Column(name = "usr_senha", nullable = false, length = 100)
        @NotNull(message = "A senha é obrigatório")
        private String senha;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getSenha() {
            return senha;
        }

        public void setSenha(String senha) {
            this.senha = senha;
        }
}

用户存储库:

public interface RepositorioUsuario extends JpaRepository<Usuario, Long> {

    Usuario findByEmail(String email);
}

安全配置:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String userQuery;

    @Value("${spring.queries.roles-query")
    private String roleQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth
        .jdbcAuthentication().usersByUsernameQuery(userQuery)
        .authoritiesByUsernameQuery(roleQuery)
        .dataSource(dataSource)
        .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
            .authorizeRequests()
            .antMatchers("/login").permitAll()
            .antMatchers("/registration").permitAll()
            .anyRequest()
                .authenticated()
                    .and().csrf().disable()
                .formLogin()
                    .loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/")
                    .usernameParameter("email").passwordParameter("senha")
                .and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**");
    }
# Thymeleaf
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false

# Spring Data
spring.datasource.url=jdbc:mysql://localhost:3306/tw_gerenciador_tarefas?useTimezone=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update

# TomCat
server.port = 8090

# SpringSecurity
spring.queries.users-query=SELECT usr_email AS username, usr_senha AS password, 1 AS active FROM usr_usuarios WHERE usr_email=?
spring.queries.roles-query=SELECT usr_email AS username, 'ROLE_USER' AS role FROM usr_usuarios WHERE usr_email=?
public class ContaController {

    @Autowired
    private ServicoUsuario servicoUsuario;

    @GetMapping("/login")
    public String login() {
        return "conta/login";
    }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#">Gerenciador de tarefas</a>
    </nav>

    <div class="container">
        <h3>Login</h3>
        <form action="/login" method="post" class="form-signin">
            <div class="form-group">
                <div class="col-md-9">
                        <input type="text" class="form-control" placeholder="E-mail" name="email">
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-9">
                        <input type="password" class="form-control" placeholder="Senha" name="senha">
                </div>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Login</button>
            </div>
            <div class=form-group>
                <div class="col-md-9">
                    <div class="alert alert-danger" role="alert" th:if="${param.error}">
                        Não foi possivel fazer login
                    </div>
                </div>
            </div>
            <div class=form-group>
                <span>Não possui conta? <a href="/registration">Registra-se</a></span>
            </div>
        </form>
    </div>
    <script src="/webjars/jquery/3.4.1/jquery.min.js"></script>
    <script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

错误消息:

共有1个答案

禄仲渊
2023-03-14

这里。您在spring.queries.roles-query结尾处遗漏了}:

@Value("${spring.queries.roles-query")
private String roleQuery;

应该是:

@Value("${spring.queries.roles-query}")
private String roleQuery;
 类似资料:
  • 我已经创建了UserDetailsServiceImpl。在这里我得到了这个用户的用户名和角色。但我不明白问题出在哪里。我已经在数据库中尝试了sql查询。 securityconfig.java LoginController.java }

  • 我正在使用spring Boot MVC安全性和JPA Hibernate以及Thymeleaf模板引擎。我正在尝试创建一个用户登录,其中一些用户已经存储在DB(MySQL)中。只要我使用正确的凭据,就可以了。此外,当我使用正确的用户名和错误的密码时,它会显示错误消息。但当我给出一个不在表中的不存在的用户名(users)或将字段留空时,我有一个错误: ERROR 11759---[nio-8080

  • 我试图在Rails中使用“omniauth-google-oauth2”gem。我已经将我的应用程序作为web应用程序注册到云控制台,并试图使其工作,但当我试图访问以下URL时:https://accounts.google.com/oauth2/auth?response_type=code&client_id=xxx.project.googleusercontent.com&redirect

  • 我正在尝试在ec2的两个实例上设置zookeeper。如这里和这里所示。我正在尝试运行zookeeper,但失败了,出现了一个错误:命令:

  • 我尝试使用flask在MongoDB中创建字段,使用下面的代码 URI中传递了正确的凭据,但我得到以下错误 OperationFailure:身份验证失败。,完整错误:{'OK':0.0,'errMsg':'Authentication Failed.','代码':18,'代码名':'AuthenticationFailed','操作时间':Timestamp(1600853835,1),'$Cl

  • 我已经为spring boot应用程序和spring security设置了CRO,如下所示。带有Spring security和jwt令牌的Spring Boot应用程序。 我与其他域一起使用api,所以我在所有控制器上使用交叉源。 所有不需要auth-token(JWT)的api调用在以下配置中都可以正常工作。但是使用所需jwt令牌的api调用失败,错误如下。 我正在尝试添加过滤器,但它没有按