簡體   English   中英

Spring Security 5 - 登錄時出現錯誤憑據,盡管電子郵件和密碼正確無誤

[英]Spring Security 5 - Bad Credentials at Login despite correct email and password

我一直試圖解決這個問題,因為一個星期以來我試過所有的帖子但仍然無法完成這項工作。 我的SecurityConfiguration類是:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final DataSource dataSource;

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

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


    public SecurityConfiguration(BCryptPasswordEncoder bCryptPasswordEncoder, DataSource dataSource) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.dataSource = dataSource;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.
                jdbcAuthentication()
                .passwordEncoder(bCryptPasswordEncoder)
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                ;


    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {



        http.authorizeRequests().antMatchers("/","/h2-console/**","/registration","/login").permitAll()
                .antMatchers("/offer/**").access("hasRole('USER') or hasRole('ADMIN')")
                .and()
                .formLogin()
                .loginPage("/login").failureUrl("/login?error=true")
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");
        http.csrf().disable();
        http.headers().frameOptions().disable();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }
}

我有一個WebMvcConfiguration類,如下所示:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}

我只是不斷獲得“憑據不好”,並且密碼與記錄不匹配。 我可以在數據庫中看到散列密碼,並在DaoAuthenticationProvider類拋出此異常的行之前設置調試點(additionalAuthenticationChecks方法),據我所知,數據庫中的用戶詳細信息正確,但確實如此在登錄時不顯示提供的密碼為編碼...

我的登錄控制器如下:

@Controller
public class LoginController {

    private final UserAccountService userAccountService;


    public LoginController(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    @GetMapping("/login")
    public ModelAndView login( Error error){
        ModelAndView modelAndView = new ModelAndView();
        if (error != null) {
            modelAndView.setViewName("error page");
        }
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/registration")
    public ModelAndView createNewUser(@Valid UserAccount user, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView();
        UserAccount userExists = userAccountService.findUserByEmail(user.getEmail());
        if (userExists != null) {
            bindingResult
                    .rejectValue("email", "error.user",
                            "There is already a user registered with the email provided");
        }
        if (bindingResult.hasErrors()) {
            modelAndView.setViewName("registration");
        } else {
            userAccountService.saveOrUpdate(user);
            modelAndView.addObject("successMessage", "User has been registered successfully");
            modelAndView.addObject("user", new UserAccount());
            modelAndView.setViewName("registration");

        }
        return modelAndView;
    }

    @GetMapping("/admin/home")
    public ModelAndView home(){
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserAccount user = userAccountService.findUserByEmail(auth.getName());
        modelAndView.addObject("userName", "Welcome " + user.getFirstName() + " "
                + user.getLastName() + " (" + user.getEmail() + ")");
        modelAndView.addObject("adminMessage","Content Available Only for Users with Admin Role");
        modelAndView.setViewName("admin/home");
        return modelAndView;
    }

}

我的SQL查詢也正常工作,我已經在H2控制台上試了一下......

你怎么想,我做錯了?

好的,我找到了罪魁禍首:

啟動應用程序時,我用一些測試數據填充數據庫,我意識到我正在更新用戶帳戶,密碼被重新編碼...

一旦我減少了UserAccount類的“saveOrUpdate”方法的使用,我就能登錄了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM