(package name可以自定义,整个项目只能在该包下)
(别忘了勾选SQL中的Mybatis Framework,创建项目
如果没有勾选mybatis框架,就需要手动加下面代码
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
将resources中的application.properties改成application.yaml并添加以下代码
spring:
datasource:
url: jdbc:mysql://localhost:3306/book_manage
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mvc:(如果html里的静态资源路径没有static就不需要像这样配置,只是这套模板路径有static比特殊)
static-path-pattern: /static/**
mail:
host: smtp.163.com(邮箱网站的smtp)
username: 发送者用户邮箱
password: 邮箱开启smtp和pop功能后会返回一串密码
redis:(如果redis在本地则不需要配置)
host:localhost:8080
实体类、mapper(根据用户名获取密码)、service、config
@Data
public class AuthUser {
private String username;
private String role;
private String password;
}
@Mapper
public interface UserMapper {
@Select("select * from users where username = #{username}")
AuthUser getPasswordByUsername(String username);
}
@Service
public class UserAuthService implements UserDetailsService {
@Resource
UserMapper mapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
AuthUser user = mapper.getPasswordByUsername(s); //从数据库根据用户名获取密码
if(user == null)
throw new UsernameNotFoundException("登录失败,用户名或密码错误!");
return User //这里需要返回UserDetails,SpringSecurity会根据给定的信息进行比对
.withUsername(user.getUsername())
.password(user.getPassword()) //直接从数据库取的密码
.roles(user.getRole()) //用户角色
.build();
}
}
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Resource
UserAuthService service;
@Resource
DataSource dataSource;
// 配置TokenRepository
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
// tokenRepository.setCreateTableOnStartup(true); //启动时自动创建用于存储Token的表(第一次启动之后注释该行,否则报错)
return tokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().hasAnyRole("user","admin")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/doLogin")
.permitAll()
.defaultSuccessUrl("/index",true)
.and()
.rememberMe()
.rememberMeParameter("remember") //若登录表单提交remenber信息,则会被记住
.tokenRepository(persistentTokenRepository()) //存储记住我的token
.tokenValiditySeconds(60 * 60 * 24 * 7) //Token的有效时间(秒)默认为14天,这里设置改为7天
//先禁用防止跨站脚本攻击的csrf token,选择型开启
.csrf()
.disable()
.cors(); //跨域时需要
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(service)
.passwordEncoder(new BCryptPasswordEncoder());
}
}