以下是用户注册的控制器方法:
@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());
}
在用户注册期间,出现“错误凭据”错误:
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。
答案 0 :(得分:0)
将“HttpServletRequest request”参数添加到registerUser方法。
在此行之后:SecurityContextHolder.getContext()。setAuthentication(usernamePasswordAuthenticationToken);
添加以下代码行: request.getSession()。setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,SecurityContextHolder.getContext());
否则,用户将不会进入Spring Security所需的会话中。
希望这有帮助!
答案 1 :(得分:0)
我可以使用以下代码(SpringBoot 2.0.5)解决此问题:
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));
}
}
}
要使其工作最困难,我需要弄清楚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()