近期学习了一下shiro安全框架,Apache Shiro 是 Java 的一个安全(权限)框架。
• Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE 环境,也可以用在 JavaEE 环境。
• Shiro 可以完成:认证、授权、加密、会话管理、与Web 集成、缓存等。
• 详情了解:下载:shiro官网
首先需要了解shiro的大致工作原理,本人是观看了尚硅谷的shiro教学视频,对shiro进行了一个整体的了解,这个视频是免费的,大家可以去谷粒学院学习。博主也分享了网盘。视频中shiro-1主要讲原理,shiro-2主要讲应用,仔细琢磨的话,理解起来问题不大。
大致原理:前台传来用户信息封装成token ,用subject的login()方法,传给自定义的 realm进行验证(Authentication),通过验证返回认证信息对象(authenticationInfo),不通过验证返回异常。博主主要实现了shiro两个主要功能:认证(Authentication),授权(简易版)(Authorazation),并将此框架整合到博主原有的SSMDemo中,废话不说,上代码:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
·····························此处省略spring的配置·······················
<!-- Shiro Filter is defined in the spring application context: -->
<!--
1. 配置 Shiro 的 shiroFilter.
2. DelegatingFilterProxy 实际上是 Filter 的一个代理对象. 默认情况下, Spring 会到 IOC 容器中查找和
<filter-name> 对应的 filter bean. 也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id.
-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>*
</web-app>
applicationContext.xml
··············此处省略··········ssm配置
<import resource="classpath:spring-shiro.xml"/>
spring-shiro.xml配置 这里关于cookie的配置如果不需要rememberMe功能的话可以省略,楼主也没弄懂啥意思 只是在浏览器中看到了cookie,不影响整体流程的使用
<?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">
<!--
1. 配置 SecurityManager!
-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"></property>
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
</list>
</property>
<property name="rememberMeManager" ref="rememberMeManager"></property>
</bean>
<!--手动指定cookie-->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe"/>
<property name="httpOnly" value="true"/>
<property name="maxAge" value="10"/><!-- 7天 -->
</bean>
<!-- rememberMe管理器 -->
<bean id="rememberMeManager"
class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<!--注入自定义cookie(主要是设置寿命, 默认的一年太长)-->
<property name="cookie" ref="rememberMeCookie"/>
</bean>
<!--
2. 配置 CacheManager. 缓存管理器
2.1 需要加入 ehcache 的 jar 包及配置文件.
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!--认证策略 :至少有一个realms成功-->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!--
3. 配置 Realm
3.1 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean
hashalgorithmName 加密算法名称
hashIterations 加密次数
-->
<bean id="jdbcRealm" class="com.trs.shiro.JdbcRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<!--
4. 配置 LifecycleBeanPostProcessor. 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法.
-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after
the lifecycleBeanProcessor has run: -->
<!--
5. 启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用.
-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<bean name="myFormAuthenticationFilter" class="com.trs.filter.MyFormAuthenticationFilter"/>
<!--
6. 配置 ShiroFilter.
6.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/admin/login.jsp"/>
<property name="successUrl" value="/admin/main.jsp"/>
<property name="unauthorizedUrl" value="/admin/404.jsp"/>
<!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
1). anon 可以被匿名访问
2). authc 必须认证(即登录)后才可能访问的页面.
3). logout 登出.
4). roles 角色过滤器
-->
<!--<property name="filters">
<map>
<entry key="authc" value-ref="myFormAuthenticationFilter" />
</map>
</property>-->
<property name="filterChainDefinitions">
<value>
/resources/asserts/** = anon
/login.jsp = anon
#这里要说一点 登录接口一定要匿名访问,博主当时就忘了配置这里,导致session相关获取异常,绕了好大的弯子
/admin/login = anon
/admin/logout = logout
#user拦截器认证和记住我都可以访问
/admin/404.jsp = user
# everything else requires authentication:
/** = authc
</value>
</property>
</bean>
</beans>
配置走通之后就可以写业务逻辑了,首先从表单前台页面开始:博主用的jsp,用html+thymeleaf也可以
<form class="form-signin" action="<%=request.getContextPath() %>/admin/login" method="post">
<img class="mb-4" src="<%=request.getContextPath()%>/resources/asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">学生成绩管理系统</h1>
<!--判断-->
<c:if test="${msg !=null}">
<p style="color: red" >${msg}</p>
</c:if>
<label class="sr-only">用户名</label>
<input type="text" name="username" class="form-control" placeholder="用户名" required="" autofocus="">
<label class="sr-only">密码</label>
<input type="password" name="password" class="form-control" placeholder="密码" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" name="remember" value="1"> 记住我
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
然后是登录接口:
大致流程分析:
1.获取当前的subject.调用security.getsubject();
2.测试当前的用户是否已经被认证 isAuthenticated();
3.若没有被认证,则把用户名和密码封装为UsernamepasswordToken 对象
1) 创建一个表单页面
2) 把请求提交到springmvc 的handler
3) 获取用户名和密码
4.执行登录:调用subject的login(authenticationToken)方法
5.自定义realm的方法,从数据库中获取对应的记录,返回给shirio
1)实际上需要继承org.apache.shiro.realm.authenticatingRealm类
2)实现dogetauthenticaitonInfo(authenticationToken)方法
6.由shiro完成对密码的比对
package com.trs.controller;
import com.trs.BaseController;
import com.trs.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController{
private static final Logger log = LoggerFactory.getLogger(LoginController.class);
@GetMapping("login")
public ModelAndView loginView() {
return new ModelAndView("/admin/login");
}
@PostMapping(value = "login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam(value = "remember",required = false) String remember
,HttpSession session){
Subject subject = SecurityUtils.getSubject();
// 把用户名和密码封装为 UsernamePasswordToken 对象
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
String msg = null;
try {
log.info ("rememberMe:{}",remember);
// rememberme
if (!StringUtils.isEmpty (remember)){
token.setRememberMe(true);
}
// 执行登录.
subject.login(token);
if (subject.isAuthenticated ()){
//获取身份信息
User user = (User) subject.getPrincipal();
session.setAttribute ("loginUser",user);
return "redirect:/admin/main.jsp";
}
} // 所有认证时异常的父类.
catch (IncorrectCredentialsException e) {
msg = "登录密码错误." + token.getPrincipal();
} catch (LockedAccountException e) {
msg = "帐号已被锁定." + token.getPrincipal();
} catch (DisabledAccountException e) {
msg = "帐号已被禁用." + token.getPrincipal();
} catch (ExpiredCredentialsException e) {
msg = "帐号已过期. " + token.getPrincipal();
} catch (UnknownAccountException e) {
msg = "帐号不存在." + token.getPrincipal();
} catch (UnauthorizedException e) {
msg = "您没有得到相应的授权!" + e.getMessage();
}
request.setAttribute ("msg",msg);
return "/admin/login";
}
}
subject.login(token)方法就会被配置的realm拦截到,由其来认证
JdbcRealm的doGetAuthenticationInfo方法
//认证操作
@Override
protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {
System.out.println("[FirstRealm] doGetAuthenticationInfo");
//1. 把 AuthenticationToken 转换为 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2. 从 UsernamePasswordToken 中来获取 username
String username = upToken.getUsername();
//3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
User user = userService.selectByUserName (username);
//4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
if(StringUtils.isEmpty (user)){
throw new UnknownAccountException ("用户不存在!");
}
//6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
//以下信息是从数据库中获取的.
//1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象.
Object principal = user;
//2). credentials: 密码.
Object credentials = user.getPassWord ();
//3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
String realmName = getName();
//4). 盐值.
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
log.info ("info的内容,{}",info);
return info;
}
2.授权 这里只做了简单的授权 博主的角色只有两个 一个admin一个user
admin查看所有菜单
//授权操作
@Override
protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {
//1. 从 PrincipalCollection 中来获取登录用户的信息
User principal = (User) principals.getPrimaryPrincipal();
//2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库)
Set<String> roles = new HashSet<> ();
roles.add("user");
if("admin".equals(principal.getUserName ())){
roles.add("admin"); //admin可以看全部
}
//3. 创建 SimpleAuthorizationInfo, 并设置其 roles 属性.
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
//4. 返回 SimpleAuthorizationInfo 对象.
return info;
}
授权jsp相关应用 简单的应用了shiro的标签
<%@ taglib prefix=“shiro” uri=“http://shiro.apache.org/tags” %>需要引入
<shiro:hasRole name="admin">
<li class="nav-item">
<a class="nav-link" href="<%=request.getContextPath()%>/stu/info/students">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
学生管理 <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=request.getContextPath()%>/score/info/scores/0">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
成绩管理
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=request.getContextPath()%>/score/info/scores/${sessionScope.loginUser.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
个人成绩查看
</a>
</li>
</shiro:hasRole>
<shiro:hasRole name="admin">
<li class="nav-item">
<a class="nav-link" href="<%=request.getContextPath()%>/score/info/scores/${sessionScope.loginUser.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
成绩查看
</a>
</li>
</shiro:hasRole>
这就是以上shiro框架的初步应用
github的源码地址仅供参考,后续打算研究一下springboot和shiro的整合,并实现复杂的角色权限菜单模块。