我在成功注册用户后实现了自动登录功能。但它停在
身份验证authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken)
没有任何错误。任何人都可以纠正我出错的地方吗?
SecurityConfiguration.java
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomSuccessHandler customSuccessHandler;
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
.usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?");
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
@Autowired
@Bean(name = "authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/*
* @Bean public DaoAuthenticationProvider authenticationProvider() {
* DaoAuthenticationProvider authenticationProvider = new
* DaoAuthenticationProvider();
* authenticationProvider.setPasswordEncoder(passwordEncoder()); return
* authenticationProvider; }
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/home/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin()
.loginPage("/login").failureUrl("/login?error").loginProcessingUrl("/j_spring_security_check")
.successHandler(customSuccessHandler).usernameParameter("username").passwordParameter("password").and()
.logout().logoutSuccessUrl("/j_spring_security_logout").and().exceptionHandling()
.accessDeniedPage("/403").and().csrf().and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(86400);
/*
* .and().exceptionHandling().accessDeniedPage("/Access_Denied");
*/ }
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
db.setDataSource(dataSource);
return db;
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
}
这是我的注册请求映射:
@RequestMapping(value = "/registerHere", method = RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("Starting register");
ModelAndView mv = new ModelAndView("/home");
mv.addObject("homePagee", "true");
String uname = user.getUsername();
if (userDAO.getUserByName(uname) == null) {
userDAO.saveOrUpdate(user);
/*
* userDAO.autologin(user.getUsername(), user.getPassword());
*/
authenticateUserAndSetSession(user, request);
}
System.out.println("ending register");
log.debug("Ending of the method registerUser");
return mv;
}
private void authenticateUserAndSetSession(Users user, HttpServletRequest request){
String username = user.getUsername();
String password = user.getPassword();
System.out.println("username: " + username + " password: " + password);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
request.getSession();
System.out.println("Line Authentication 1");
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
System.out.println("Line Authentication 2");
Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);// authenticates the token
System.out.println("Line Authentication 3");
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
System.out.println("Line Authentication 4");
}
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
System.out.println("Line Authentication 5");
session.setAttribute("username", user.getUsername());
System.out.println("Line Authentication 6");
session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());
System.out.println("username: " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());
user = userDAO.validate(user.getUsername(), user.getPassword());
log.debug("You are successfully register");
}
当我注册Console时:
Hibernate:
insert
into
Cart
(addedDate, grandTotal, usersID, cartId)
values
(?, ?, ?, ?)
Hibernate:
update
USERS
set
billingAddressId=?,
cartId=?,
email=?,
enabled=?,
mobile=?,
name=?,
password=?,
role=?,
shippingAddressId=?,
STATE=?,
username=?
where
usersID=?
username: do password: $2a$10$YX.AKZYoI0g7xAN8mzlHOurK8Hys4aX2Iw75OE.6qgpZ6PeV4qHoy
Line Authentication 1
Line Authentication 2
线路认证2之后停止了我知道缺少什么吗?
答案 0 :(得分:0)
我已经解决并回答了上述问题 在控制器中:
@RequestMapping(value = "/registerHere", method = RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("register 3");
ModelAndView mv = new ModelAndView("/home");
mv.addObject("homePagee", "true");
String uname = user.getUsername();
if (userDAO.getUserByName(uname) == null) {
String passwordFromForm = user.getPassword();
userDAO.saveOrUpdate(user);
try {
authenticateUserAndSetSession(user, passwordFromForm, request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("register 4");
log.debug("Ending of the method registerUser");
return mv;
}
控制器中的上述方法进一步定义为:
private void authenticateUserAndSetSession(Users user, String passwordFromForm, HttpServletRequest request){
String username = user.getUsername();
System.out.println("username: " + username + " password: " + passwordFromForm);
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwordFromForm, userDetails.getAuthorities());
request.getSession();
System.out.println("Line Authentication 1");
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
System.out.println("Line Authentication 2");
Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
System.out.println("Line Authentication 3");
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
System.out.println("Line Authentication 4");
}
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
System.out.println("Line Authentication 5");
session.setAttribute("username", user.getUsername());
System.out.println("Line Authentication 6");
session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());
System.out.println("username: " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());
user = userDAO.validate(user.getUsername(), user.getPassword());
log.debug("You are successfully register");
}
其他答案并没有建议把它放在try / catch中,所以没有意识到为什么逻辑在代码运行时没有工作......并且控制台上没有任何错误或异常。因此,如果你不把它放在试试中,你将不会得到不良凭证的例外。