登录工作,但表persitence_logins保留为空。我在这里关注文档:https://courses.baeldung.com/courses/learn-spring-security-the-starter-class/lectures/924437不知道如何改变。我需要覆盖其他内容吗?
persistent_logins用户名varchar(64)不为null,系列varchar(64)主键,令牌varchar(65)不为null,last_used时间戳记不为null
安全配置
package com.example.java.configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.sql.DriverManager;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private DataSource dataSource;
private final String USERS_QUERY = "select email, password, active from user where email=?";
private final String ROLES_QUERY = "select u.email, r.role from user u inner join user_role ur on (u.id = ur.user_id) inner join role r on (ur.role_id=r.role_id) where u.email=?";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.usersByUsernameQuery(USERS_QUERY)
.authoritiesByUsernameQuery(ROLES_QUERY)
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/dottore").hasAuthority("DOTTORE")
.antMatchers("/home/**").hasAnyAuthority("USER").anyRequest()
.authenticated().and().csrf().disable()
.formLogin().loginPage("/login").usernameParameter("email").passwordParameter("password")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/home/home")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.and().rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60*60)
.and().exceptionHandling().accessDeniedPage("/access_denied");
}
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
db.setDataSource(dataSource);
return db;
}
}
APPLICATION PROPERTIES
#Peristence
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=pass
# hibernate configurations
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialet= org.hibernate.dialect.MySQL5Dialect
# thumeleaf configurations
spring.thymeleaf.mode= LEGACYHTML5
spring.thymeleaf.cache=false
用户控制器:
package com.example.java.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.java.model.User;
import com.example.java.service.UserService;
import sun.jvm.hotspot.runtime.Threads;
import java.util.concurrent.TimeUnit;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/")
public ModelAndView main(){
ModelAndView model = new ModelAndView();
model.setViewName("user/login");
return model;
}
@RequestMapping(value= {"/login"}, method=RequestMethod.GET)
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("user/login");
return model;
}
@RequestMapping(value= {"/signup"}, method=RequestMethod.GET)
public ModelAndView signup() {
ModelAndView model = new ModelAndView();
User user = new User();
model.addObject("user", user);
model.setViewName("user/signup");
return model;
}
@RequestMapping(value= {"/signup"}, method=RequestMethod.POST)
public ModelAndView createUser(@Valid User user, BindingResult bindingResult) throws InterruptedException {
ModelAndView model = new ModelAndView();
User userExists = userService.findUserByEmail(user.getEmail());
if(userExists != null) {
bindingResult.rejectValue("email", "error.user", "This email already exists!");
}
if(bindingResult.hasErrors()) {
model.setViewName("user/signup");
} else {
userService.saveUser(user);
model.addObject("msg", "User has been registered successfully!");
model.addObject("user", new User());
model.setViewName("user/signup");
}
return model;
}
@RequestMapping(value= {"/home/home"}, method=RequestMethod.GET)
public ModelAndView home() {
ModelAndView model = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
model.addObject("userName", user.getNome() + " " + user.getCognome());
model.setViewName("home/home");
return model;
}
@RequestMapping(value= {"/access_denied"}, method=RequestMethod.GET)
public ModelAndView accessDenied() {
ModelAndView model = new ModelAndView();
model.setViewName("errors/access_denied");
return model;
}
}
编辑:解决。
在我放入的安全配置中:
.and().rememberMe().rememberMeParameter("my-remember-me")
并且在login.html中
<input type="checkbox" class="form-check-input" name="my-remember-me" id="remember-me" />