JavaWeb项目中Shiro权限框架的使用

No.1 首先在pom,xml文件中导入依赖:

<?xml version="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.0</modelVersion>    <groupId>com.zzx</groupId>   <artifactId>MavenJavaWeb</artifactId>   <version>1.0-SNAPSHOT</version>   <packaging>war</packaging>    <dependencies>     <dependency>       <groupId>org.slf4j</groupId>       <artifactId>slf4j-simple</artifactId>       <version>1.7.21</version>     </dependency>     <dependency>       <groupId>org.slf4j</groupId>       <artifactId>jcl-over-slf4j</artifactId>       <version>1.7.21</version>     </dependency>     <dependency>       <groupId>org.apache.shiro</groupId>       <artifactId>shiro-core</artifactId>       <version>1.2.2</version>     </dependency>     <!--这是JavaWeb项目使用的jar包-->     <dependency>       <groupId>commons-logging</groupId>       <artifactId>commons-logging</artifactId>       <version>1.1.3</version>     </dependency>     <dependency>       <groupId>javax.servlet</groupId>       <artifactId>javax.servlet-api</artifactId>       <version>3.0.1</version>     </dependency>     <dependency>       <groupId>org.apache.shiro</groupId>       <artifactId>shiro-web</artifactId>       <version>1.2.2</version>     </dependency>   </dependencies> </project> 

No.2 然后在resources中创建shiro-author-realm.ini,代码如下:

#声明一个 realm myAuthorRealm=com.zzx.realm.MyAuthorRealm #指定 securityManager 的 realms 实现 securityManager.realms=$myAuthorRealm 

No.3 在realm中创建MyAuthorRealm,代码如下:

package com.zzx.realm;  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.subject.PrincipalCollection;  import java.util.HashSet; import java.util.Set;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 16:17  * @desc  */ public class MyAuthorRealm extends AuthorizingRealm {      /**      * 授权      * @param principals 身份信息集合      * @return AuthorizationInfo 返回当前用户的角色与权限信息      */     @Override     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {         //1.获得身份         String principal =(String) principals.getPrimaryPrincipal();          //2.根据身份(账号)查角色,         //Set<String> roles = service.findByRolesUsername(principal);         Set<String> roles = new HashSet<>();         roles.add("role1");         roles.add("role2");          //3.再根据角色查权限         //Set<String> permissions = new HashSet<>();         //for (String role : roles) {         //    permissions.addAll()         // }         Set<String> permissions = new HashSet<>();         permissions.add("/select");         permissions.add("/add");         permissions.add("/delete");         permissions.add("/update");          //4.将角色,权限封装进info对象         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();         info.addRoles(roles);         info.addStringPermissions(permissions);         return info;     }      /**      * 认证      * @param token 当subject.login(token)----->Login方法的token赋值给      *              doGetAuthenticationInfo(token)      * @return 如果登录成功,返回认证信息      * @throws AuthenticationException 认证异常,如果登录信息有误,自行抛出异常      */     @Override     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {         //从token中获得用户名与密码         String principal =(String) token.getPrincipal();    //获得身份-用户名         char[] credentials =(char[]) token.getCredentials();          //凭证会自动编程:字符数组         System.out.println("凭证 - "+ credentials);          //通过用户名和密码查询数据库         //通过查询数据库得到的数据与登录时输入的信息对比         if (!"admin".equals(principal)){             //如果失败,抛出AuthenticationException             throw new UnknownAccountException();         }else {             if ("123456".equals(credentials)){                 //如果失败,IncorrectCredentialsException                 throw new IncorrectCredentialsException();             }         }         //如果成功,就封装成AuthenticationInfo返回         /**          * info中封装的数据          * 1.身份          * 2.凭证          * 3.当前realmName          */         System.out.println(getName());         return new SimpleAuthenticationInfo(principal,credentials,getName());     } }  

No.4 创建一个简单的登录Servlet:

package com.zzx.servlet;  import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 21:37  * @desc  */ @WebServlet("/login")       //使用此注解就不用在web.xml中配置路径了 public class LoginServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         IniSecurityManagerFactory securityManagerFactory =                 new IniSecurityManagerFactory("classpath:shiro-author-realm.ini");          SecurityManager instance = securityManagerFactory.getInstance();          SecurityUtils.setSecurityManager(instance);          //从SecurityUtils中获得主体         Subject subject = SecurityUtils.getSubject();          //模拟登录,输入用户名密码         String name = req.getParameter("name");         String password = req.getParameter("password");         UsernamePasswordToken token = new UsernamePasswordToken(name, password);          //登录         try {             subject.login(token);             //登录成功查询全部             resp.sendRedirect("/select");             System.out.println("登录成功");         } catch (UnknownAccountException e) {             System.out.println("用户名不存在");             e.printStackTrace();         }catch (IncorrectCredentialsException e){             System.out.println("密码错误");             e.printStackTrace();         }     } }  

No.5 创建简单的登出Servlet:

package com.zzx.servlet;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 22:10  * @desc  */ @WebServlet("/logout") public class LogoutServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         System.out.println("/LogOut");     } } 

No.6创建简单的查询Servlet:

package com.zzx.servlet;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 22:08  * @desc  */ @WebServlet("/select") public class SelectServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         System.out.println("/Select");     } } 

No.7创建简单的添加Servlet:

package com.zzx.servlet;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 22:05  * @desc  */ @WebServlet("/add") public class AddServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         System.out.println("/add");     } }  

No.8创建简单的删除Servlet:

package com.zzx.servlet;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 22:06  * @desc  */ @WebServlet("/delete") public class DeleteServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         System.out.println("/delete");     } }  

No.9创建简单的修改Servlet:

package com.zzx.servlet;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  /**  * @auther ZhengZiXuan  * @date 2021/3/25 22:07  * @desc  */ @WebServlet("/update") public class UpdateServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         System.out.println("/update");     } }  

No.10 在webapp下创建index.jsp:

<html> <body> <h2>Hello World!</h2> </body> </html> 

No.11 在webapp下创建error.jsp:

<%--   Created by IntelliJ IDEA.   User: rooy   Date: 2021/3/25   Time: 22:26   To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head>     <title>Title</title> </head> <body> <h1>错误页面</h1> </body> </html> 

No.12 在resources下创建shiro-web.ini :

[main] authc.loginUrl=/login roles.unauthorizedUrl=/error.jsp perms.unauthorizedUrl=/error.jsp  [users] zhangsan=123456,role1,role2 lisi=123456,role2  [roles] role1=/select,/add,/delete,/update role2=/select #authc:用户   roles:角色    perms:权限 [urls] /login=anon /logout=logout /error.jsp=anon /index.jsp=anon /add=authc /delete=authc,roles[role1],perms["/delete"] /update=authc,roles[role1],perms["/update"] 

No.13然后在web.xml中配置相关配置:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xmlns="http://java.sun.com/xml/ns/javaee"          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"          version="2.5">    <display-name>Archetype Created Web Application</display-name>   <welcome-file-list>     <welcome-file>index.jsp</welcome-file>   </welcome-file-list>   <!--Shiro的监听器-->   <listener>     <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>   </listener>   <!--加载Shiro的配置文件-->   <context-param>     <param-name>shiroConfigLocations</param-name>     <!--shiroConfigLocations 默认是:"/WEB-INF/shiro.ini"-->     <param-value>classpath:shiro-web.ini</param-value>   </context-param>   <filter>     <filter-name>ShiroFilter</filter-name>     <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>   </filter>   <filter-mapping>     <filter-name>ShiroFilter</filter-name>     <url-pattern>/*</url-pattern>   </filter-mapping> </web-app>  

No.14 在项目中配置Tomcat
No.15在浏览器中的地址栏上直接发送请求即可;
  登录:
http://localhost:8080/login?name=zhangsan&password=123456
  查询:
http://localhost:8080/select
  添加:
http://localhost:8080/add
  删除:
http://localhost:8080/delete
  修改:
http://localhost:8080/update
ps:
 1.如果没有登录或者登录的用户没有权限的话,浏览器地址栏会自动跳转到:http://localhost:8080/login
 2.如果登录的用户执行了登出的请求:http://localhost:8080/logout之后,若再执行增删改的方法,会自动跳转到登录界面,http://localhost:8080/login

版权声明:玥玥 发表于 2021-03-27 7:29:30。
转载请注明:JavaWeb项目中Shiro权限框架的使用 | 女黑客导航