我使用此模板https://github.com/hellokoding/registration-login-spring-xml-maven-jsp-mysql進行註冊。Spring Security - 註冊
控制器
@RequestMapping(value = "/register", method = POST)
public String registration(@ModelAttribute("userForm") User userForm) {
userService.add(userForm);
securityService.autologin(userForm.getUsername(), userForm.getPassword());
return "redirect:/notes/";
}
方法自動登錄:
@Override
public void autologin(final String username, final String password) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
方法loadUserByUsername:
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
User user = userRepository.findByName(username);
Set<GrantedAuthority> grantedAuthorities = user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toSet());
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
HTTP配置:
<http auto-config="true" >
<intercept-url pattern="/notes**" access="authenticated" />
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/auth**" access="permitAll" />
<intercept-url pattern="/accessDenied" access="permitAll" />
<access-denied-handler error-page="/accessDenied" />
<logout logout-success-url="/auth/login?logout" />
<form-login
default-target-url="/notes/"
login-page="/auth/login"
login-processing-url="/j_spring_security_check"
username-parameter="username"
password-parameter="password"
/>
<remember-me data-source-ref="dataSource" />
<session-management session-fixation-protection="newSession" >
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
</http>
但是,當我創建一個帳戶,之後「註冊」頁面,我去上的「符號」。並且這個用戶被添加到數據庫。但是,我必須重定向:/ notes /。
刪除'默認目標url',並添加一些[AuthenticationSuccessHandler](http://docs.spring.io/spring-安全/網站/文檔/電流/ apidocs /組織/ springframework的/安全/網絡/認證/ AuthenticationSuccessHandler.html)做重定向基於誰連接(即委託人) –
我這樣做,但我有同樣的效果。我也嘗試改變控制器中的返回值,以「重定向:/ NotesWeb/notes /」,但這也沒有改變任何東西。 – jack
我沒有看到'NotesWeb'必須在這裏做什麼。你改變了你的問題,現在你想重定向到'/ notes'?也許'usernamePasswordAuthenticationToken.isAuthenticated()'爲false,所以沒有通過身份驗證登錄頁面(你應該看到在應用程序日誌中) –