2016-11-03 10 views
1

は、ユーザ登録のためのコントローラのメソッドである:ここで春ブーツ:どのようにユーザー登録後に自動ログインをしますか?ここ

@PostMapping("register_user") 
public void registerUser(@RequestParam String email, @RequestParam String password, @RequestParam String name, 
         @RequestParam String info, HttpServletResponse response) throws EmailExistsException, IOException { 
    userRepository.save(new User(email, new BCryptPasswordEncoder().encode(password), name, info)); 
    try { 
     UserDetails userDetails = customUserDetailsService.loadUserByUsername(email); 
     UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); 
     authenticationManager.authenticate(usernamePasswordAuthenticationToken); 
     if (usernamePasswordAuthenticationToken.isAuthenticated()) { 
      SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); 
      log.debug(String.format("Auto login %s successfully!", email)); 
     } 
    } catch (Exception e) { 
     log.error(e.getMessage(), e); 
    } 
    response.sendRedirect("/"); 
} 

はSecurityConfigからconfigureメソッドです:

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder()); 
} 

ユーザー登録時に "不正な資格証明書" のエラーがあります:

org.springframework.security.authentication.BadCredentialsException: Bad credentials 
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE] 
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE] 
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE] 
at s7.controller.ActionController.registerUser(ActionController.java:45) ~[main/:na] 
は、

登録後、ユーザーはエラーなしでログインできます。私は間違って何をしていますか?

P.S.私もこのトピックのように自動ログインを試みた:Auto login after successful registration しかし、私は同じBadCredentialsExceptionがあります。

私がコメントする場合はauthenticationManager.authenticate(usernamePasswordAuthenticationToken);、ユーザー意志正しいauthentication.getPrincipalを持つ任意のBadCredentialsExceptionなしで自動ログイン()。

+1

http://stackoverflow.com/questions/3813028/auto-login-after-successful-registeration –

+1

@AfsunKhammadli私は既にこのトピックを試しましたが、同じエラーがあります。 –

答えて

0

registerUserメソッドに 'HttpServletRequest request'パラメータを追加します。右この行の後

:。SecurityContextHolder.getContext()setAuthentication(usernamePasswordAuthenticationToken)。

このコード行を追加します。 request.getSession()。setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY、SecurityContextHolder.getContext());

そうでない場合、ユーザは、春のセキュリティが必要とするセッションではありません。

このヘルプが必要です。

関連する問題