一、pom.xml中导入资源jar
使用生成进行添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
外部导入
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
二、创建config配置类替代spring配置文件
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
/**
* 配置信息放行资源
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//资源放行
http.authorizeRequests().antMatchers("/login.html", "403.html", "/css/**", "/js/**", "/img/**", "/plugins/**").permitAll();
//设置资源必须登录成功后进行访问
http.authorizeRequests().antMatchers("/**").authenticated();
//角色认证,角色名不加 ROLE_ ,系统自动添加
http.authorizeRequests().antMatchers("/**").hasAnyRole("USER", "ADMIN");
//设置登录页面
http.formLogin().defaultSuccessUrl("/to/index")//登录成功
.loginPage("/login.html")//设置登录页面,没有的话采用框架自带页面
.loginProcessingUrl("/login")//登录url,固定login
.usernameParameter("username")//账号
.passwordParameter("password")//密码
.failureUrl("/login.html");//登录失败
//关闭跨域
http.csrf().disable();
//设置退出登录
http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");
//配置403异常处理
http.exceptionHandling().accessDeniedPage("/403.html");
}
/**
* 认证数据管理:连接认证 service
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}
三、创建service接口继承 UserDetailsService 类 ,实现类重写loadUserByUsername方法
public interface UserService extends UserDetailsService {
}
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用持久层获取用户登录信息
Users loginuser = userDao.findUserByUsername(username);
User user = new User(loginuser.getUsername(),loginuser.getPassword(),loginuser.getStatus()==1,true,true,true,getRoles(loginuser.getRoleList()));
return user;
}
/**
* 封装用户角色
* @param roleList
* @return
*/
private Collection<? extends GrantedAuthority> getRoles(List<Role> roleList) {
ArrayList<GrantedAuthority> alist = new ArrayList<>();
for (Role role : roleList) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
alist.add(authority);
}
return alist;
}
@Bean
//定义加密器
public PasswordEncoder createPasswordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
四、前端权限验证
<!DOCTYPE html>
//导入命名空间
<html lang="en" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<base href="http://localhost:8081/"/>
<title>Title</title>
</head>
<body>
这是主页
标签进行授权认证
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('ROLE_USER')">
普通用户
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
管理员用户
</div>
</body>
</html>