目录
2.1 添加spring-shiro.xml文件(Spring与Shiro集成)添加到main\resources目录下
2.2 修改web.xml文件,添加shiroFilter的配置
2.3 shiro开启注解配置(必须将Shiro注解的开启放置到spring-mvc.xml中(即放在springMVC容 器中加载),不然Shiro注解开启无效!!!)
- "1.0" encoding="UTF-8"?>
-
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0modelVersion>
-
- <groupId>com.jmhgroupId>
- <artifactId>mybatis03artifactId>
- <version>1.0-SNAPSHOTversion>
- <packaging>warpackaging>
-
- <name>mybatis03 Maven Webappname>
-
- <url>http://www.example.comurl>
-
- <properties>
- <spring.version>5.0.2.RELEASEspring.version>
- <maven.compiler.source>1.8maven.compiler.source>
- <maven.compiler.target>1.8maven.compiler.target>
- <jackson.version>2.9.3jackson.version>
- <shiro.version>1.2.5shiro.version>
- <slf4j.version>1.7.7slf4j.version>
- <log4j2.version>2.9.1log4j2.version>
- properties>
-
- <dependencies>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-coreartifactId>
- <version>${spring.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-beansartifactId>
- <version>${spring.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>${spring.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-ormartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>${spring.version}
- version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-aspectsartifactId>
- <version>${spring.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webartifactId>
- <version>${spring.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webmvcartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>jstlgroupId>
- <artifactId>jstlartifactId>
- <version>1.2version>
- dependency>
- <dependency>
- <groupId>taglibsgroupId>
- <artifactId>standardartifactId>
- <version>1.1.2version>
- dependency>
-
-
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-databindartifactId>
- <version>${jackson.version}version>
- <exclusions>
- <exclusion>
- <artifactId>jackson-annotationsartifactId>
- <groupId>com.fasterxml.jackson.coregroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-coreartifactId>
- <version>${jackson.version}version>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-annotationsartifactId>
- <version>${jackson.version}version>
- dependency>
-
-
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.3.3version>
- dependency>
-
-
- <dependency>
- <groupId>org.hibernategroupId>
- <artifactId>hibernate-validatorartifactId>
- <version>6.0.7.Finalversion>
- dependency>
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.12version>
- <scope>testscope>
- dependency>
-
-
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>4.0.0version>
- <scope>providedscope>
- dependency>
-
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>3.4.5version>
- dependency>
-
-
-
- <dependency>
- <groupId>com.github.pagehelpergroupId>
- <artifactId>pagehelperartifactId>
- <version>5.1.2version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>1.3.1version>
- dependency>
-
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.44version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-dbcp2artifactId>
- <version>2.1.1version>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-pool2artifactId>
- <version>2.4.3version>
- dependency>
-
-
-
-
- <dependency>
- <groupId>org.slf4jgroupId>
- <artifactId>slf4j-apiartifactId>
- <version>${slf4j.version}version>
- dependency>
- <dependency>
- <groupId>org.slf4jgroupId>
- <artifactId>jcl-over-slf4jartifactId>
- <version>${slf4j.version}version>
- <scope>runtimescope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-apiartifactId>
- <groupId>org.slf4jgroupId>
- exclusion>
- exclusions>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-slf4j-implartifactId>
- <version>${log4j2.version}version>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-apiartifactId>
- <groupId>org.slf4jgroupId>
- exclusion>
- exclusions>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-coreartifactId>
- <version>${log4j2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-apiartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-webartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- <dependency>
- <groupId>com.lmaxgroupId>
- <artifactId>disruptorartifactId>
- <version>3.2.0version>
- dependency>
-
-
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>1.18.20version>
- <scope>providedscope>
- dependency>
-
-
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-coreartifactId>
- <version>${shiro.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-webartifactId>
- <version>${shiro.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-springartifactId>
- <version>${shiro.version}version>
- dependency>
-
-
-
-
- dependencies>
-
-
-
-
-
-
- <build>
- <finalName>shiro02finalName>
- <resources>
-
- <resource>
- <directory>src/main/javadirectory>
- <includes>
- <include>**/*.xmlinclude>
- includes>
- resource>
-
- <resource>
- <directory>src/main/resourcesdirectory>
- <includes>
- <include>jdbc.propertiesinclude>
- <include>*.xmlinclude>
- includes>
- resource>
- resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.mybatis.generatorgroupId>
- <artifactId>mybatis-generator-maven-pluginartifactId>
- <version>1.3.2version>
- <dependencies>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.44version>
- dependency>
- dependencies>
- <configuration>
- <overwrite>trueoverwrite>
- configuration>
- plugin>
- plugins>
- pluginManagement>
- build>
- project>
- "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="shiroRealm" class="com.jmh.shiro.utils.Realm">
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/home/index.shtml"/>
-
-
-
-
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /book/**=authc
- /common/**=authc
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
- beans>
<import resource="spring-shiro.xml"/>
-
-
- <filter>
- <filter-name>shiroFilterfilter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
- <init-param>
-
- <param-name>targetFilterLifecycleparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>shiroFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
- depends-on="lifecycleBeanPostProcessor">
- <property name="proxyTargetClass" value="true">property>
- bean>
- <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
- <property name="securityManager" ref="securityManager"/>
- bean>
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <prop key="org.apache.shiro.authz.UnauthorizedException">
- unauthorized
- prop>
- props>
- property>
- bean>
- package com.jmh.shiro.utils;
-
- import com.jmh.shiro.model.User;
- import com.jmh.shiro.service.IUserService;
- 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.apache.shiro.util.ByteSource;
-
- import javax.annotation.Resource;
- import java.net.Authenticator;
- import java.util.Set;
-
- public class Realm extends AuthorizingRealm {
- //注入
- @Resource
- private IUserService iUserService;
-
- /**
- * 提供授权信息
- * @param pc
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
- //获取用户名
- String str = (String) pc.getPrimaryPrincipal();
- //根据用户名获取角色
- Set
roles = iUserService.findRoles(str); - //根据用户名获取权限
- Set
permissions = iUserService.findPermissions(str); - //将角色和权限信息设置到SimpleAuthorizationInfo
- SimpleAuthorizationInfo simpl=new SimpleAuthorizationInfo();
- simpl.setRoles(roles);
- simpl.setStringPermissions(permissions);
- return simpl;
- }
-
- /**
- * 提供认证信息
- * @param token
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- //从令牌中获取用户名
- String username = (String)token.getPrincipal();
- //通过用户名去数据库获取用户对应信息
- User user = iUserService.selectByUserName(username);
- //判断用户信息不为空
- if(null==user){
- throw new RuntimeException("用户信息为空");
- }
- //保存用户认证信息
- SimpleAuthenticationInfo siml=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return siml;
- }
- }
- package com.jmh.shiro.controller;
-
- import com.jmh.shiro.model.User;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.authz.annotation.Logical;
- import org.apache.shiro.authz.annotation.RequiresRoles;
- import org.apache.shiro.subject.Subject;
- import org.hibernate.validator.constraints.EAN;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.http.HttpSession;
-
- @Controller
- @RequestMapping("/login")
- public class LoginController {
-
- /**
- * 点击登录跳转登录页面
- */
- @RequestMapping("toLogin")
- public String toLogin(){
- return "login";
- }
- /**
- * 登录验证方法
- */
- @RequestMapping("/login")
- public String login(User user, HttpSession httpSession){
- //获取主体
- Subject subject = SecurityUtils.getSubject();
- //使用登录令牌
- UsernamePasswordToken upt=new UsernamePasswordToken(user.getUsername(),user.getPassword());
- try {
- //使用主体登录
- subject.login(upt);
- //将用户名保存到作用域
- httpSession.setAttribute("msg",user.getUsername());
- }catch (RuntimeException e){
- throw new RuntimeException("账号或密码错误");
- }
- //验证成功
- return "loginIndex";
- }
- /**
- * 点击退出
- */
- @RequestMapping("/toLoginOut")
- public String toLoginOut(){
- //获取主体
- Subject subject=SecurityUtils.getSubject();
- //使用主体退出
- subject.logout();
- return "index";
- }
-
- /**
- * 未认证游客通道
- */
- @RequestMapping("/toNot")
- public String toNot(){
- return "loginIndex";
- }
-
- /**
- * 使用角色跳转页面
- */
- @RequestMapping("/toGj")
- @RequiresRoles(value = {"管理员","高级用户"},logical = Logical.OR)
- public String toGj(){
- return "gj";
- }
-
- }
- <%--
- Created by IntelliJ IDEA.
- User: 蒋明辉
- Date: 2022/8/19
- Time: 22:56
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>首页title>
- head>
- <body>
- <h1>成功访问主页h1>
- <hr/>
- <a href="<%=request.getContextPath()%>/login/toLogin">点击登录a>
- body>
- html>
- <%--
- Created by IntelliJ IDEA.
- User: 蒋明辉
- Date: 2022/8/20
- Time: 1:18
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>登录title>
- head>
- <body>
- <div style="color: red">${msg}div>
- <form action="<%=request.getContextPath()%>/login/login" method="post">
- 账 号: <input type="text" name="username"/><br/>
- 密 码: <input type="password" name="password"/><br/>
- <input type="submit" value="登录">
- form>
- body>
- html>
导入Shiro标签库
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- <%--
- Created by IntelliJ IDEA.
- User: 蒋明辉
- Date: 2022/8/20
- Time: 1:30
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@taglib prefix="s" uri="http://shiro.apache.org/tags" %>
- <html>
- <head>
- <title>个人主页title>
- head>
- <body>
- <s:authenticated>
- <h1>恭喜${msg}!登录成功h1>
- s:authenticated>
- <%--根据角色--%>
- <s:hasRole name="普通用户">
- <a href="#">普通用户a>
- s:hasRole>
- <s:hasRole name="高级用户">
- <a href="#">高级用户a>
- s:hasRole>
- <s:hasRole name="管理员">
- <a href="<%=request.getContextPath()%>/login/toGj">管理员a>
- s:hasRole>
- <%--<hr/>--%>
- <%--根据权限--%>
- <s:hasPermission name="书本查询">
- <h2>书本查询h2>
- s:hasPermission>
- <%--未登陆(未认证)--%>
- <s:notAuthenticated>
- <h2>未认证用户h2>
- s:notAuthenticated>
- <%--已登录(已认证)--%>
- <s:authenticated>
- <a href="<%=request.getContextPath()%>/login/toLoginOut">点击我退出a>
- s:authenticated>
- body>
- html>
- <%--
- Created by IntelliJ IDEA.
- User: 蒋明辉
- Date: 2022/8/21
- Time: 18:08
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>未授权title>
- head>
- <body>
- <h1>权限不足!!!不可此操作h1>
- body>
- html>
- <%--
- Created by IntelliJ IDEA.
- User: 蒋明辉
- Date: 2022/8/21
- Time: 18:04
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>高级用户管理员title>
- head>
- <body>
- <h1>高级用户,管理员h1>
- body>
- html>
guest标签 :验证当前用户是否为“访客”,即未认证(包含未记住)的用户
user标签 :认证通过或已记住的用户authenticated标签 :已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在
notAuthenticated标签 :未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户principal 标签 :输出当前用户信息,通常为登录帐号信息
hasRole标签 :验证当前用户是否属于该角色
lacksRole标签 :与hasRole标签逻辑相反,当用户不属于该角色时验证通过
hasAnyRole标签 :验证当前用户是否属于以下任意一个角色hasPermission标签 :验证当前用户是否拥有指定权限
lacksPermission标签 :与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过
@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示当前Subject需要角色admin和user
@RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b