简体   繁体   中英

Spring Security always redirecting to failureUrl()

Registration in my project works and the correct password is saved. When I copy paste this password to make a test method, the hash comparison works perfectly. But when I try to login, I'm always redirected to the failureUrl mapping:

private static final String CLOUD_MAPPING = "/profile/cloud";
private static final String LOGIN_MAPPING = "/login";
private static final String LOGOUT_MAPPING = "/logout";

 @Autowired
public WebSecurityConfig(UserService userService) {
    this.userService = userService;
}

@Bean(name = "passwordEncoder")
public static PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

/**
 * Méthode configAuthentication() permettant de préciser le service à appeler pour valider
 * l'authentification d'un utilisateur par Spring Security
 * @param auth Objet Spring Security AuthenticationManagerBuilder
 * @throws Exception Exception retournée si une erreur survient
 */
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}

/**
 * Méthode configure() permettant de configurer l'accès aux différentes pages de l'application
 * et de préciser les paramètres d'authentification de Supnote
 * @param http Objet HttpSecurity utilisé par Spring Security
 * @throws Exception Exception retournée si une erreur survient
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers(PROFILE_MAPPING).authenticated()
            .antMatchers(ADMIN_MAPPING).hasAuthority(adminRole)
            .anyRequest().permitAll()
        .and()
            .formLogin().loginPage(LOGIN_MAPPING).defaultSuccessUrl(CLOUD_MAPPING).loginProcessingUrl("/login").failureUrl(LOGIN_MAPPING + "?error=true")
            .usernameParameter("emailAddress").passwordParameter("password")
        .and()
            .rememberMe()
            .key("remember-key")
            .rememberMeCookieName("remember-me")
            .rememberMeParameter("remember-me")
            .tokenValiditySeconds(24 * 60 * 60)
        .and()
            .logout()
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutUrl(LOGOUT_MAPPING)
            .logoutSuccessUrl(LOGIN_MAPPING)
        .and()
            .csrf()
        .and()
            .sessionManagement().maximumSessions(1).expiredUrl(LOGIN_MAPPING);
}

This is the form in the login view:

<form th:action="@{/login}" method="post" class="form-signin">
    <fieldset class="form-group">
        <legend class="form-signin-heading text-center" th:text="${msgLogin}"></legend>

        <div class="alert alert-danger" role="alert" th:if="${#httpServletRequest.getParameter('error') != null}">Les identifiants saisis sont incorrects</div>
            <div class="form-group">
                <label for="emailAddress">Email</label>
                <input type="text" id="emailAddress" name="emailAddress" class="form-control" placeholder="Adresse email" required="required" autofocus="autofocus" />
            </div>

            <div class="form-group">
                <label for="password">Mot de passe</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="Mot de passe" required="required" />
            </div>

            <div class="checkbox">
                <label>
                    <input type="checkbox" id="remember-me" name="remember-me" /> Se souvenir de moi
                </label>
            </div>

            <div class="form-group text-center">
                <input type="submit" value="Connexion" class="btn btn-primary btn-lg" />
            </div>

            <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
        </fieldset>
    </form>

Here is the LOGIN_MAPPING method in the controller:

@GetMapping("/login")
public ModelAndView prepareLogin() {
    // Récupération de l'objet Spring Security Authentication associé à l'utilisateur actuel
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(MSG_LOGIN_ATTR, "Indiquez vos indentifiants");
    // Si l'utilisateur est authentifié, il sera automatiquement redirigé vers /profile/cloud
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        modelAndView.setViewName("redirect:/profile/cloud");
        return modelAndView;
    }
    modelAndView.setViewName("login");
    return modelAndView;
}

Here is the CLOUD_MAPPING method in the controller:

@GetMapping("/profile/cloud")
public ModelAndView getCloud() {

    User user = userService.getLoggedAccount();

    ModelAndView mav = new ModelAndView("cloud");
    mav.addObject("folders", user.getFolders());

    return mav;
}

Did I forget something?

Thank you very much for your help.

Try it into spring security config: //defaultSuccessUrl : This is URL you want redirect when login success. It must map in controller. Example i want redirect to design and show all design. I write to bellow. .formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/design")

User.

@Data
@Entity
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@RequiredArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "USERNAME")
    private final String username;
    @Column(name = "PASSWORD")
    private final String password;
    @Column
    private long salary;
    @Column
    private int age;

    private String email;
}

RegisterUser:

@Data
public class RegisterUser {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String username;
    private String password;

    public User toUser(PasswordEncoder passwordEncoder) {
        return new User(username,passwordEncoder.encode(password));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM