目录
1.5 Authentication 和 Authorization方法
一 shiro基本原理
1.1 简介
Apache Shiro 是一个强大且易用的 Java 安全框架
Shiro可以帮我们完成 :认证、授权、加密、会话管理、与 Web 集成、缓存等。
主要功能:
Subject(用户):当前的操作用户 获取当前用户Subject sj = SecurityUtils.getSubject()
SecurityManager(安全管理器):Shiro的核心,负责与其他组件进行交互,实现 subject 委托的各种功能
Realms(数据源) :Realm会查找相关数据源,充当与安全管理间的桥梁,经过Realm找到数据源进行认证,授权等操作
Authenticator(认证器): 用于认证,从 Realm 数据源取得数据之后进行执行认证流程处理。
Authorizer(授权器):用户访问控制授权,决定用户是否拥有执行指定操作的权限。
SessionManager (会话管理器):支持会话管理
CacheManager (缓存管理器):用于缓存认证授权信息
Cryptography(加密组件):提供了加密解密的工具包
1.2 ShiroFilter 的工作原理
1.3 shiro中的过滤器
过滤器的名称 | Java 类 |
anon | org.apache.shiro.web. lter.authc.AnonymousFilter |
authc | org.apache.shiro.web. lter.authc.FormAuthenticationFilter |
logout | org.apache.shiro.web. lter.authc.LogoutFilter |
perms | org.apache.shiro.web. lter.authz.PermissionsAuthorizationFilter |
anon: 匿名处理过滤器,即不需要登录即可访问;一般用于静态资源过滤;/static/**=anon
authc: 表示需要认证(登录)才能使用;(放最后) /**=authc
logout: 注销过滤器 /logout=logout
roles: 角色授权过滤器,验证用户是否拥有资源角色;
1.4 Shiro三大组件
1、Subject :当前用户的操作
2、SecurityManager:用于管理所有的Subject
3、Realms:用于进行权限信息的验证
1.5 Authentication 和 Authorization方法
在shiro的用户权限认证过程中其通过两个方法来实现:
1、Authentication:是验证用户身份的过程。
2、Authorization:是授权访问控制,用于对用户进行的操作进行人证授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
1.6 shiro的工作流程
1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断
1.7 shiro的优点有哪些?
1、简单的身份验证,支持多种数据源
2、对角色的简单授权,支持细粒度的授权(方法)
3、支持一级缓存,以提升应用程序的性能
4、内置基于POJO的企业会话管理,适用于web及非web环境
5、非常简单的API加密
6、不跟任何框架绑定,可以独立运行
二 集成spring
2.1 基础配置
web.xml文件添加如下
<!-- shiro权限 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>*.action</url-pattern>
<url-pattern>*.html</url-pattern>
<url-pattern>*</url-pattern>
</filter-mapping>
添加配置文件applicationContext_shiro.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login.html" />
<property name="unauthorizedUrl" value="/error.html" />
<property name="filterChainDefinitions">
<value>
/error.html = anon
/*.html = authc
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="gztRealm"></property>
</bean>
<bean id="gztRealm" class="com.gztpay.resource.filter.GztRealm">
</bean>
</beans>
2.2 使用方式
新建工具类GztRealm.java,代码如下:
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;import com.gztpay.resource.bean.Menu;
import com.gztpay.resource.bean.UserLogin;
import com.gztpay.resource.service.MenuService;
import com.gztpay.resource.service.UserLoginService;
public class GztRealm extends AuthorizingRealm{
@Autowired
private UserLoginService loginService;
@Autowired
private MenuService menuService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
//得到令牌
UsernamePasswordToken token = (UsernamePasswordToken) arg0;
String username = token.getUsername();
String password = new String(token.getPassword());
UserLogin login = loginService.login(username, password);
if (login == null) {
return null;
}
return new SimpleAuthenticationInfo(login, password, getName());
}@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("执行了授权方法....");
UserLogin userLogin = (UserLogin) arg0.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
List<Menu> menus = menuService.searchMenusByParentId("0");
for (Menu menu : menus) {
info.addStringPermission(menu.getMenuname());
}
System.out.println("结束了授权方法....");
return info;
}}
新建controller类,内容如下:
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import com.gztpay.resource.bean.UserLogin;
import com.gztpay.resource.service.UserLoginService;
import com.gztpay.utils.FastJsonUtils;@Controller
@RequestMapping("user")
public class UserLoginController {
@Autowired
private UserLoginService loginService;/**
* 用户登录
*
* @param model
* @param session
* @param username
* @param password
* @return
*/
@RequestMapping("login")
public String login(Model model, HttpSession session, String username, String password) {
model.addAttribute("username", username);
// 1 创建令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 2 获取subject(主题)
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
// 执行认证
try {
subject.login(token);// 会跳到我们自定义的realm中
session.setAttribute("username", username);
UserLogin userLogin = (UserLogin) subject.getPrincipal();
model.addAttribute("name", userLogin.getName());
return "index";
} catch (Exception e) {
model.addAttribute("userError", "用户名或密码错误!");
session.setAttribute("username", username);
return "login";
}
}/**
* 安全退出
*
* @param session
* @return
*/
@RequestMapping("loginOut")
public String loginOut(HttpSession session) {
try {
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
subject.logout();
} catch (Exception e) {
e.printStackTrace();
}
return "login";
}
/**
* 角色管理
*/
@RequestMapping("toRole")
public String role() {
return "role";
}@RequestMapping("listByPage")
public void listByPage(HttpServletResponse response) {
List<UserLogin> list = loginService.findUser();
FastJsonUtils.write_json(response, list);
}/**
* 修改密码
*/
@RequestMapping("editPwd")
public void editPwd(HttpServletResponse response, HttpSession session, String newpass, String pwd) {
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
UserLogin userLogin = (UserLogin) subject.getPrincipal();
int i = loginService.editPwd(userLogin.getUsername(), pwd, newpass);
if (i == 0) {
FastJsonUtils.write_json(response, "原密码输入错误,请重新输入");
} else {
FastJsonUtils.write_json(response, "修改成功!");
}
}
}
三 集成springboot
3.1 导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
3.2 配置实现
新建ShiroConfig.java类,代码如下:
package com.test.config;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.HashMap;
import java.util.Map;@Configuration
public class ShiroConfig {
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}//将自己的验证方式加入容器
@Bean
public ShiroRealm myShiroRealm() {
ShiroRealm customRealm = new ShiroRealm();
return customRealm;
}//权限管理,配置主要是Realm的管理认证
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}//Filter工厂,设置对应的过滤条件和跳转条件
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterMap = new HashMap<String, String>();
// 登出
filterMap.put("/logout", "logout");
// swagger
filterMap.put("/swagger**/**", "anon");
filterMap.put("/webjars/**", "anon");
filterMap.put("/v2/**", "anon");
// 对所有用户认证
filterMap.put("/**", "authc");
// 登录
shiroFilterFactoryBean.setLoginUrl("/loginPage");
// 首页
shiroFilterFactoryBean.setSuccessUrl("/index");
// 错误页面,认证不通过跳转
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
// 免登陆地址
filterMap.put("/swagger-resources/**", "anon");
filterMap.put("/favicon.ico", "anon");
filterMap.put("/agreement", "anon");
filterMap.put("/privacy", "anon");
filterMap.put("/webjars/**", "anon");
filterMap.put("/lay/**", "anon");
filterMap.put("/js/**", "anon");
filterMap.put("/image/**", "anon");
filterMap.put("/error", "anon");
filterMap.put("/login", "anon");
filterMap.put("/register", "anon");
filterMap.put("/api/login", "anon");
filterMap.put("/system/user/findPwd", "anon");
filterMap.put("/sendCode", "anon");
filterMap.put("/api/sendCode", "anon");
filterMap.put("/logout", "anon");
filterMap.put("/api/logout", "anon");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
新建ShiroRealm.java类,内容如下:
package com.test.config;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;import com.test.entity.Menu;
import com.test.entity.Role;
import com.test.entity.User;
import com.test.service.UserService;public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* @MethodName doGetAuthorizationInfo
* @Description 权限配置类
* @Param [principalCollection]
* @Return AuthorizationInfo
* @Author WangShiLin
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了授权方法....");
User user = (User) principals.getPrimaryPrincipal();
//添加角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for (Role role : user.getRoles()) {
//添加角色
simpleAuthorizationInfo.addRole(role.getName());
//添加权限
for (Menu menu : role.getMenus()) {
simpleAuthorizationInfo.addStringPermission(menu.getMenuName());
}
}
System.out.println("结束了授权方法....");
return simpleAuthorizationInfo;
}/**
* @MethodName doGetAuthenticationInfo
* @Description 认证配置类
* @Param [authenticationToken]
* @Return AuthenticationInfo
* @Author WangShiLin
* @RequiresPermissions("create")
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
return null;
}
//获取用户信息
String name = authenticationToken.getPrincipal().toString();
User user = userService.findUsername(name);
if (user == null) {
//这里返回后会报出对应异常
return null;
} else {
//这里验证authenticationToken和simpleAuthenticationInfo的信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
return simpleAuthenticationInfo;
}
}
}
新建controller类,代码如下:
package com.test.controller;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import com.test.entity.User;
import com.test.utils.R;import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class UserController {@PostMapping("/login")
public R login(@RequestParam(value = "account") String account,
@RequestParam(value = "password") String password) {
Subject userSubject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(account, password);
try {
// 登录验证
userSubject.login(token);
return R.ok();
} catch (UnknownAccountException e) {
return R.failed("账户不存在");
} catch (DisabledAccountException e) {
return R.failed("账户不可用");
} catch (IncorrectCredentialsException e) {
return R.failed("账户无权限");
} catch (Throwable e) {
e.printStackTrace();
return R.failed("用户名或密码错误");
}
}@GetMapping("/role")
@RequiresRoles("super")
public String role() {
return"超级管理员角色";
}@GetMapping("/permission")
@RequiresPermissions(value = {"add", "update"}, logical = Logical.AND)
public String permission() {
return"新增或编辑权限";
}
}