spring 安全自动登录不工作
AutoLogin with spring security Not Working
我在成功注册用户后实现了自动登录功能。但它停止于
身份验证 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");
}
当我注册控制台时:
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: a$YX.AKZYoI0g7xAN8mzlHOurK8Hys4aX2Iw75OE.6qgpZ6PeV4qHoy
Line Authentication 1
Line Authentication 2
它在线路验证 2 后停止知道我缺少什么吗?
我已经解决了上面问题的答案是
在控制器中:
@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 中,因此人们不明白为什么逻辑在代码运行时不起作用......控制台上没有任何错误或异常。因此,如果您不将其放入 try catch 中,您将不会收到错误凭证的异常。
我在成功注册用户后实现了自动登录功能。但它停止于
身份验证 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");
}
当我注册控制台时:
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: a$YX.AKZYoI0g7xAN8mzlHOurK8Hys4aX2Iw75OE.6qgpZ6PeV4qHoy
Line Authentication 1
Line Authentication 2
它在线路验证 2 后停止知道我缺少什么吗?
我已经解决了上面问题的答案是 在控制器中:
@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 中,因此人们不明白为什么逻辑在代码运行时不起作用......控制台上没有任何错误或异常。因此,如果您不将其放入 try catch 中,您将不会收到错误凭证的异常。