我的项目中的注册有效,并且保存了正确的密码。当我复制粘贴此密码以形成测试方法时,哈希比较可以正常工作。但是当我尝试登录时,我总是重定向到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;
}
我忘记了什么吗?
非常感谢您的帮助。
答案 0 :(得分:0)
尝试进入spring安全配置: // defaultSuccessUrl:这是您要在登录成功时重定向的URL。它必须在控制器中映射。示例我想重定向到设计并显示所有设计。我写信给贝娄。 .formLogin()。loginPage(“ / login”)。permitAll()。defaultSuccessUrl(“ / design”)
用户。
@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));
}
}