簡體   English   中英

Spring Security總是重定向到failureUrl()

[英]Spring Security always redirecting to failureUrl()

在我的項目中注冊成功,並且保存了正確的密碼。 當我復制粘貼此密碼以形成測試方法時,哈希比較可以正常工作。 但是,當我嘗試登錄時,我總是被重定向到failureUrl映射:

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

這是登錄視圖中的表單:

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

這是控制器中的LOGIN_MAPPING方法:

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

這是控制器中的CLOUD_MAPPING方法:

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

    User user = userService.getLoggedAccount();

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

    return mav;
}

我忘記了什么嗎?

非常感謝您的幫助。

將其嘗試到spring安全配置中:// defaultSuccessUrl:這是您要在登錄成功時重定向的URL。 它必須在控制器中映射。 示例我想重定向到設計並顯示所有設計。 我寫信給貝婁。 .formLogin()。loginPage( “/登錄”)。permitAll()。defaultSuccessUrl( “/設計”)

用戶。

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

暫無
暫無

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

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