Java Spring Boot:用户注册后如何自动登录?
以下是用于用户注册的控制器方法:Java Spring Boot:用户注册后如何自动登录?,java,spring-security,spring-boot,Java,Spring Security,Spring Boot,以下是用于用户注册的控制器方法: @PostMapping("register_user") public void registerUser(@RequestParam String email, @RequestParam String password, @RequestParam String name, @RequestParam String info, HttpServletResponse response) throws Ema
@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中的配置方法:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
用户注册过程中出现“错误凭据”错误:
注册后,用户可以登录没有任何错误。我做错了什么
另外,我也尝试过像这样的自动登录:
但我也有同样的坏证件例外
如果我注释authenticationManager.authenticate(usernamePasswordAuthenticationToken)代码>,用户将自动登录,无任何BadCredentialsException,并具有正确的身份验证。getPrincipal() 将'HttpServletRequest'参数添加到registerUser方法 紧跟在这一行之后:SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken) 添加这行代码: request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,SecurityContextHolder.getContext()) 否则,用户将不会处于Spring Security所需的会话中
希望这有帮助 我使用以下代码(SpringBoot 2.0.5)解决了这个问题: 对我来说,最难理解的是AuthenticationManager。您必须自动连接在spring安全配置中设置的同一个AuthenticationManager,如下所示,不要忘记自动连接服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UsuarioService usuarioService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/registration*").permitAll()
.anyRequest().hasAnyAuthority("MASTER")
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.csrf().disable()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "/files/**", "/forgot-password"");
}
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(usuarioService);
}
@Bean
public AuthenticationManager authManager() throws Exception {
return this.authenticationManager();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
}
最后一个问题花了我一段时间才解决。如果使用“web.ignoring()”安全上下文添加注册端点,则将不存在,并且您将无法登录该用户。因此,请确保将其添加为.antMatchers(“/registration*”).permitAll()@AfsunKhammadli我已经尝试过这个主题,但也有相同的错误。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class SecurityService {
@Autowired
@Lazy
AuthenticationManager authManager;
private Logger logger = LoggerFactory.getLogger(SecurityService.class);
public void doLogin(String username, String password) {
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
Authentication authentication = authManager.authenticate(authRequest);
if (authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.debug(String.format("Auto login successfully!", username));
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UsuarioService usuarioService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/registration*").permitAll()
.anyRequest().hasAnyAuthority("MASTER")
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.csrf().disable()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "/files/**", "/forgot-password"");
}
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(usuarioService);
}
@Bean
public AuthenticationManager authManager() throws Exception {
return this.authenticationManager();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
}