java小白一个,为了不让东拼西凑的塑料springboot知识遗忘,斗胆开始写博客,方便日后ctrl+c/v
首先引入security的pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
接着配置application.yml,笔者采用mysql+mybatis
mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver//笔者的mysql版本是8.0注意驱动与老版不同
mybatis:
mapper-locations: classpath:mapping/*.xml//这里笔者在resources文件夹下新建了一个mapping文件夹
type-aliases-package: com.example.demo.model
创建实体,这里笔者偷懒了数据库各位照着Users自建一下吧,dao层也是嘿嘿
@Data
public class Users implements UserDetails {
private Long id;
private String username;
private String password;
private boolean enable;
private String roles;
private static final long serialVersionUID = 1L;
private List<GrantedAuthority> authorities;
public void setAuthorities(List<GrantedAuthority> authorities){
this.authorities=authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return this.enable;
}
}
业务层
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UsersDao usersDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users user=usersDao.selectByUserName(username);
if(user==null)throw new UsernameNotFoundException("用户不存在");
user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
//在数据库中笔者是没有authorities列的,当时查找资料整了好半天不懂,原来是在业务层中将role的值赋给了authorities
return user;
}
}
配置类
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception{
http.cors()
.and()
.authorizeRequests()
.antMatchers("/select/**").hasRole("ADMIN")
.and()
.formLogin()
.and()
.rememberMe().userDetailsService(userDetailsService());
http.csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}//不加这个方法笔者之前一直报错,日后整明白了原理再回来补
}
/*
* 这里作者在控制层做了一个"/select"接口对应上面的拦截"/select/**"
* 当我们启动程序在浏览器中输入localhost:8080/select就会弹出security默认登陆页面,有效期为JSESSIONID存活时间
* */
好了关键部分已经写出来了,或许日后会更新更详细的,白