目录
10 整合 SpringSecurity安全框架
登录和拦截
补充:前端权限验证
11 整合Shiro(面试)
Shiro简介
一、Hello World
GitHub快速搭建:
https://github.com/apache/shiro/tree/master/samples/quickstart/
1.导入依赖
相关配置文件2.log4j.properties
3.shiro.ini
4.启动类 Quickstart
二、SpringBoot 集成 Shiro
1.pom.xml
2.MyController:测试环境是否正常
3.index.html页面
三、spring整合shiro
1.pom.xml
2.UserRealm:提供认证和授权的方法
3.ShiroConfig:配置类
1.注册UserRealm到容器(创建realm对象,realm需要自定义类)
2.注册DefaultWebSecurityManager,作为中间件关联realm
3.注册ShiroFilterFactoryBean关联DefaultWebSecurityManager,用来实现shiro的内置过滤器,(请求专门在这个地方过滤)
四、Shiro实现登录拦截
1.基本方法
2.设置自有认证了才能访问到这几个接口
3.login.html:登录页面
4.MyController:添加去往登录页接口
5.在ShiroConfig:setLoginUrl如果没有认证,去到登录页
五、Shiro实现用户认证
1.MyController
获取当前用户subject = SecurityUtils.getSubject();
封装用户信息new UsernamePasswordToken(username,password);
执行登录subject.login(token);
2.login.html
3.UserRealm:登录认证
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
userToken 与数据库值进行比较
六、Shiro整合Mybatis
1.导入依赖
2.配置application.ym
3.UserRealm连接真实数据库
七、Shiro 实现用户授权
1.ShiroConfig
ShiroConfig中的getShiroFilterFactoryBean方法添加认证代码
2.MyController:添加为授权页面
4.ShiroConfig中的getShiroFilterFactoryBean方法中添加
5.UserRealm类的修改
//拿到当前登录的这个对象 Subject subject = SecurityUtils.getSubject(); User currentUser = (User)subject.getPrincipal();//拿到user对象
需要验证这里传user,授权getPrincipal可会有值
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
八、Shiro整合Thymeleaf
1.shiro-thymeleaf整合包导入——官网
2.在ShiroConfig中整合ShiroDialect
3.index.html页面
九、Shiro案例的所有代码
1.ShiroConfig
2.UserRealm
3.MyController
4.pom依赖
10 整合 SpringSecurity安全框架
SpringSecurity环境搭建
在web开发中安全第一位!接着过滤器,拦截器~ 功能性需求:否 做网站(安全第一位),因为存在漏洞会泄露隐私 shiro和SpringSecurity很像,除了类和名称不一样 认证,授权(vip1,vip2,vip3) - 功能权限 - 访问权限 - 菜单权限 - ……拦截器,过滤器:大量的原生代码(冗余)
简介
SpringSecurity 是针对spring项目的安全框架,也是springboot底层默认的安全模块技术选型,它可以实现强大的Web安全机制,只需要少数的spring-boot--spring-security依赖,进行少量的配置,就可以实现强大的安全管理
org.springframework.boot spring-boot-starter-security
记住几个类 :
WebSecurityConfigurerAdapter:自定义Security策略 AuthenticationManagerBuilder:自定义认证策略 @EnableWebSecurity:开启WebSecurity模式【@Enablexxxx:开启某个功能】
SpringSecurity的两个主要目标认证(en)和授权(or)【访问控制】
认证方式:Authentication 权限:Authorization
SpringSecurity (里面有很多版本可以选)
Spring 安全参考手册
认证和授权
控制器controller
@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;
}
}
写一个类继承WebSecurityConfigurerAdapter,使用@EnableWebSecurity开启web安全服务
- 地址授权:使用HttpSecurity security
- 账户认证和给予权限:使用AuthenticationManagerBuilder builder
- SpringSecurity5 以后默认需要密码加密方式,推荐使用passwordEncoder(new BCryptPasswordEncoder())
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
// url授权: HttpSecurity
@Override
protected void configure(HttpSecurity security) throws Exception {
// 首页所有人可以访问,但是功能也只有对有权限的人可以访问
security
.authorizeRequests() // 认证请求
.antMatchers("/").permitAll()
.antMatchers("/level1
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
// 读取配置文件:
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
// 获取当前的用户对象 Subject
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过当前用户拿到Shiro的Session 可以脱离web存值取值
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
//判断当前的用户是否被认证
if (!currentUser.isAuthenticated()) {
//Token 令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//设置记住我
token.setRememberMe(true);
try {
//执行登录操作
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
// 检查角色
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
//粗粒度
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
//细粒度
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
二、SpringBoot 集成 Shiro
1.pom.xml
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
2.MyController:测试环境是否正常
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
}
3.index.html页面
首页
首页
add | update
org.springframework.boot spring-boot-starter-thymeleaforg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest org.junit.vintage junit-vintage-engine
2.MyController:测试环境是否正常
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
}
3.index.html页面
首页
首页
add | update
首页
首页
add | update
三、spring整合shiro
1.pom.xml
org.apache.shiro
shiro-spring
1.5.3
2.UserRealm:提供认证和授权的方法
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
return null;
}
}
3.ShiroConfig:配置类
1.注册UserRealm到容器(创建realm对象,realm需要自定义类)
2.注册DefaultWebSecurityManager,作为中间件关联realm
3.注册ShiroFilterFactoryBean关联DefaultWebSecurityManager,用来实现shiro的内置过滤器,(请求专门在这个地方过滤)
创建realm对象,需要自定义类
DefaultWebSecurityManager
ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {
//3. shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//2. DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//1. 创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
四、Shiro实现登录拦截
1.基本方法
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有记住我功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
2.设置自有认证了才能访问到这几个接口
Map filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
3.login.html:登录页面
登录页面
登录
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
return null;
}
}
3.ShiroConfig:配置类
1.注册UserRealm到容器(创建realm对象,realm需要自定义类)
2.注册DefaultWebSecurityManager,作为中间件关联realm
3.注册ShiroFilterFactoryBean关联DefaultWebSecurityManager,用来实现shiro的内置过滤器,(请求专门在这个地方过滤)
创建realm对象,需要自定义类
DefaultWebSecurityManager
ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {
//3. shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//2. DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//1. 创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
四、Shiro实现登录拦截
1.基本方法
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有记住我功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
2.设置自有认证了才能访问到这几个接口
Map filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
3.login.html:登录页面
登录页面
登录
2.注册DefaultWebSecurityManager,作为中间件关联realm
3.注册ShiroFilterFactoryBean关联DefaultWebSecurityManager,用来实现shiro的内置过滤器,(请求专门在这个地方过滤)
创建realm对象,需要自定义类
DefaultWebSecurityManager
ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {
//3. shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//2. DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//1. 创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
四、Shiro实现登录拦截
1.基本方法
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有记住我功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
2.设置自有认证了才能访问到这几个接口
Map filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
3.login.html:登录页面
登录页面
登录
创建realm对象,需要自定义类
DefaultWebSecurityManager
ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {
//3. shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//2. DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//1. 创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
四、Shiro实现登录拦截
1.基本方法
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有记住我功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
2.设置自有认证了才能访问到这几个接口
Map filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
3.login.html:登录页面
登录页面
登录
anon: 无需认证就可以访问 authc: 必须认证了才能访问 user: 必须拥有记住我功能才能用 perms: 拥有对某个资源的权限才能访问 role: 拥有某个角色权限
2.设置自有认证了才能访问到这几个接口
Map filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
3.login.html:登录页面
登录页面
登录
登录页面
登录
4.MyController:添加去往登录页接口
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
5.在ShiroConfig:setLoginUrl如果没有认证,去到登录页
//设置登录的请求
bean.setLoginUrl("/toLogin");
五、Shiro实现用户认证
1.MyController
-
获取当前用户subject = SecurityUtils.getSubject();
-
封装用户信息new UsernamePasswordToken(username,password);
-
执行登录subject.login(token);
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
2.login.html
登录页面
登录
//设置登录的请求
bean.setLoginUrl("/toLogin");
五、Shiro实现用户认证
1.MyController
-
获取当前用户subject = SecurityUtils.getSubject();
-
封装用户信息new UsernamePasswordToken(username,password);
-
执行登录subject.login(token);
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
2.login.html
登录页面
登录
-
获取当前用户subject = SecurityUtils.getSubject();
-
封装用户信息new UsernamePasswordToken(username,password);
-
执行登录subject.login(token);
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
2.login.html
登录页面
登录
3.UserRealm:登录认证
-
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
-
userToken 与数据库值进行比较
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
// 用户名、密码, 数据中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (!userToken.getUsername().equals(name)) {
return null;//抛出异常 UnknownAccountException
}
// 密码认证,shiro做
return new SimpleAuthenticationInfo("",password,"");
}
六、Shiro整合Mybatis
1.导入依赖
org.projectlombok
lombok
mysql
mysql-connector-java
log4j
log4j
1.2.17
com.alibaba
druid
1.1.23
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
2.配置application.ym
spring:
datasource:
username: root
password: admin
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
type-aliases-package: nuc.ss.pojo
mapper-locations: classpath:mapper
//拦截
Map filterMap = new LinkedHashMap<>();
//filterMap.put("/user/add","authc");
//filterMap.put("/user/update","authc");
//授权,正常情况下,没有授权会跳转到为授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//为授权页面
bean.setUnauthorizedUrl("/noauto");
return bean;
}
//DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
// 整合ShiroDialect: 用来整合 Shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
return new ShiroDialect();
}
}
2.UserRealm
package nuc.ss.config;
import nuc.ss.pojo.User;
import nuc.ss.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal();//拿到user对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// 虚拟用户
//String name = "root";
//String password = "123456";
//if (!userToken.getUsername().equals(name)) {
// return null;//抛出异常 UnknownAccountException
//}
// 真实数据库 用户名、密码, 数据中取
User user = userService.queryUserByName(userToken.getUsername());
if (user == null) {//没有这个人
return null;
}
//首页
//Subject currentSubject = SecurityUtils.getSubject();
//Session session = currentSubject.getSession();
//session.setAttribute("loginUser",user);
// 密码认证,shiro做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
3.MyController
package nuc.ss.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauto")
@ResponseBody
public String unauthorized() {
return "未经授权,无法访问此页面";
}
}
4.pom依赖
4.0.0
nuc.ss
shiro-springboot
0.0.1-SNAPSHOT
shiro-springboot
Demo project for Spring Boot
1.8
UTF-8
UTF-8
2.3.0.RELEASE
com.github.theborakompanioni
thymeleaf-extras-shiro
2.0.0
org.projectlombok
lombok
mysql
mysql-connector-java
log4j
log4j
1.2.17
com.alibaba
druid
1.1.23
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
org.apache.shiro
shiro-spring
1.5.3
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
1.8
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
userToken 与数据库值进行比较
org.projectlombok lombokmysql mysql-connector-javalog4j log4j1.2.17 com.alibaba druid1.1.23 org.mybatis.spring.boot mybatis-spring-boot-starter2.1.3
2.配置application.ym
spring:
datasource:
username: root
password: admin
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
type-aliases-package: nuc.ss.pojo
mapper-locations: classpath:mapper
//拦截
Map filterMap = new LinkedHashMap<>();
//filterMap.put("/user/add","authc");
//filterMap.put("/user/update","authc");
//授权,正常情况下,没有授权会跳转到为授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//为授权页面
bean.setUnauthorizedUrl("/noauto");
return bean;
}
//DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象,需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
// 整合ShiroDialect: 用来整合 Shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
return new ShiroDialect();
}
}
2.UserRealm
package nuc.ss.config;
import nuc.ss.pojo.User;
import nuc.ss.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal();//拿到user对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// 虚拟用户
//String name = "root";
//String password = "123456";
//if (!userToken.getUsername().equals(name)) {
// return null;//抛出异常 UnknownAccountException
//}
// 真实数据库 用户名、密码, 数据中取
User user = userService.queryUserByName(userToken.getUsername());
if (user == null) {//没有这个人
return null;
}
//首页
//Subject currentSubject = SecurityUtils.getSubject();
//Session session = currentSubject.getSession();
//session.setAttribute("loginUser",user);
// 密码认证,shiro做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
3.MyController
package nuc.ss.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauto")
@ResponseBody
public String unauthorized() {
return "未经授权,无法访问此页面";
}
}
4.pom依赖
4.0.0
nuc.ss
shiro-springboot
0.0.1-SNAPSHOT
shiro-springboot
Demo project for Spring Boot
1.8
UTF-8
UTF-8
2.3.0.RELEASE
com.github.theborakompanioni
thymeleaf-extras-shiro
2.0.0
org.projectlombok
lombok
mysql
mysql-connector-java
log4j
log4j
1.2.17
com.alibaba
druid
1.1.23
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
org.apache.shiro
shiro-spring
1.5.3
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
1.8
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
package nuc.ss.config;
import nuc.ss.pojo.User;
import nuc.ss.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal();//拿到user对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// 虚拟用户
//String name = "root";
//String password = "123456";
//if (!userToken.getUsername().equals(name)) {
// return null;//抛出异常 UnknownAccountException
//}
// 真实数据库 用户名、密码, 数据中取
User user = userService.queryUserByName(userToken.getUsername());
if (user == null) {//没有这个人
return null;
}
//首页
//Subject currentSubject = SecurityUtils.getSubject();
//Session session = currentSubject.getSession();
//session.setAttribute("loginUser",user);
// 密码认证,shiro做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
3.MyController
package nuc.ss.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取一个用户
Subject subject = SecurityUtils.getSubject();
// 封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
} catch (UnknownAccountException e) {//用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e) {//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauto")
@ResponseBody
public String unauthorized() {
return "未经授权,无法访问此页面";
}
}
4.pom依赖
4.0.0
nuc.ss
shiro-springboot
0.0.1-SNAPSHOT
shiro-springboot
Demo project for Spring Boot
1.8
UTF-8
UTF-8
2.3.0.RELEASE
com.github.theborakompanioni
thymeleaf-extras-shiro
2.0.0
org.projectlombok
lombok
mysql
mysql-connector-java
log4j
log4j
1.2.17
com.alibaba
druid
1.1.23
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
org.apache.shiro
shiro-spring
1.5.3
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
1.8
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
4.0.0 nuc.ss shiro-springboot0.0.1-SNAPSHOT shiro-springboot Demo project for Spring Boot 1.8 UTF-8 UTF-8 2.3.0.RELEASE com.github.theborakompanioni thymeleaf-extras-shiro2.0.0 org.projectlombok lombokmysql mysql-connector-javalog4j log4j1.2.17 com.alibaba druid1.1.23 org.mybatis.spring.boot mybatis-spring-boot-starter2.1.3 org.apache.shiro shiro-spring1.5.3 org.springframework.boot spring-boot-starter-thymeleaforg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest org.junit.vintage junit-vintage-engineorg.springframework.boot spring-boot-dependencies${spring-boot.version} pom import org.apache.maven.plugins maven-compiler-plugin1.8 1.8 UTF-8 org.springframework.boot spring-boot-maven-plugin



