源码地址:https://github.com/hpp3501/springboot.git
教程视频资源:https://www.bilibili.com/video/BV1PE411i7CV?p=34
简介
Spring Security,这是一种基于 Spring AOP 和 Servlet 过滤器的安全框架。它提供全面的安全性解决方案,同时在 Web 请求级和方法调用级处理身份确认和授权。
环境搭建
1. 准备好页面
2. 创建路由控制层
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/", "/index"})
public String index() {
return "index";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id) {
return "views/level1/" + id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id) {
return "views/level2/" + id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id) {
return "views/level3/" + id;
}
}
运行成功是这样的
源码文章开头已经给出了。接下来将实现用户认证和授权,以及权限控制,不同级别权限的用户只能访问相应级别的页面。
授权和认证
package com.kuang.config;
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;
//开去授权认证
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有有权限的人才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
//拥有vip1权限的人才可以访问 /level1 下的所有文件
.antMatchers("/level1/**").hasRole("vip1")
//拥有vip2权限的人才可以访问 /level2 下的所有文件
.antMatchers("/level2/**").hasRole("vip2")
//拥有vip3权限的人才可以访问 /level3 下的所有文件
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认去登录页,这里的登录页是系统内置的,也可以指定自己的登录页
http.formLogin();
//记住我
http.rememberMe();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//正常情况应该使用auth.jdbcAuthentication(),从数据库获取用户及角色
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//给此用户分配权限 vip2 和 vip3,结合上面的授权,kuangshen这个用户只能访问level2 和 level3下的页面
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
这个时候登录"kuangshen"这个用户就访问不了level1下的页面,访问的话回提示403禁止访问的错误,如下图。
不过可以访问level2下的页面,如下图
注销账户
根据权限显示页面
怎么根据用户的权限去显示其有权限查看的页面,没权限查看的页面直接隐藏掉。可以整合security-thymeleof,具体使用方法可以百度,很简单的。