安全验证框架shiro(二)

2019-08-07 11:48:14 浏览数 (1)

这里主要说的是在web中的开发

同样引用一段图片和说明

Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”;

SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。

Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;

Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;

Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;

SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器);

SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能;

CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能

Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的。

同样创建maven-web项目,大致结构如下:

pom.xml如下:

代码语言:javascript复制
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.shiro</groupId>
  <artifactId>shiro-web</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>shiro-web Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <shiro.version>1.2.4</shiro.version>
  </properties>

  <dependencies>
		<dependency>  
           <groupId>javax.servlet</groupId>  
           <artifactId>jstl</artifactId>  
           <version>1.1.2</version>  <!-- 1.2 -->
       </dependency>
       <dependency>  
           <groupId>taglibs</groupId>  
           <artifactId>standard</artifactId>  
           <version>1.1.2</version>  
       </dependency> 

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>		
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <version>3.1.0</version>
		    <scope>provided</scope>
		</dependency>
		
	 <dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<version>1.7.19</version>
	 </dependency>
	 
	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
	</dependency>
	
	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.2</version>
	</dependency>
	
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.38</version>
	</dependency>
	
     <dependency>  
	    <groupId>org.apache.commons</groupId>  
	    <artifactId>commons-lang3</artifactId>  
	    <version>3.4</version>  
	</dependency> 	
	
<!--     <dependency>  
	    <groupId>com.fasterxml.jackson.core</groupId>  
	    <artifactId>jackson-core</artifactId>  
	    <version>2.8.1</version>  
	</dependency>  
	  
	<dependency>  
	    <groupId>com.fasterxml.jackson.core</groupId>  
	    <artifactId>jackson-databind</artifactId>  
	    <version>2.8.1</version>  
	</dependency>  
	  
	<dependency>  
	    <groupId>com.fasterxml.jackson.core</groupId>  
	    <artifactId>jackson-annotations</artifactId>  
	    <version>2.8.1</version>  
	</dependency> --> 
<!-- 	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-core-asl</artifactId>
	    <version>1.9.13</version>
	</dependency>
	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-core-lgpl</artifactId>
	    <version>1.9.13</version>
	</dependency> -->
	
	<dependency>
	    <groupId>net.sf.json-lib</groupId>
	    <artifactId>json-lib</artifactId>
	    <version>2.4</version>
	    <classifier>jdk15</classifier>
	</dependency>		 		
    
	  <dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-core</artifactId>
		<version>${shiro.version}</version>
	  </dependency>
	  <dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-web</artifactId>
		<version>${shiro.version}</version>
	  </dependency>	      
  </dependencies>
  
  <build>
   <finalName>shiro-web</finalName>
  	<plugins>
		<plugin>
			<groupId>org.apache.tomcat.maven</groupId>
         		<artifactId>tomcat7-maven-plugin</artifactId>
         		<version>2.2</version>
			<configuration>
				<uriEncoding>UTF-8</uriEncoding>
				<port>80</port>
				<path>/shiro</path>
			</configuration>
		</plugin>  	
  		<plugin>
 			<groupId>org.apache.maven.plugins</groupId>  
	        <artifactId>maven-compiler-plugin</artifactId>  
	        <configuration>  
	          <source>1.7</source>  
	          <target>1.7</target>  
	        </configuration>
  		</plugin>
  	</plugins>
  </build>

</project>

然后开始配置web.xml文件

代码语言:javascript复制
<?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_3_0.xsd" version="3.0">

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	
	
	<context-param>
		<param-name>shiroConfigLocations</param-name>
	    <param-value>/WEB-INF/configs/ini/shiro.ini</param-value>
	    <!-- <param-value>/WEB-INF/configs/ini/shiro-jdbc.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>
	
	<servlet>
		<servlet-name>login</servlet-name>
		<servlet-class>com.shiro.servlet.LoginServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>login</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
	 
	<listener>
		<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
	</listener>
</web-app>

由于使用的ini配置文件读取用户信息,所以加入org.apache.shiro.web.env.EnvironmentLoaderListener,

然后就是对应的shiro.ini文件:

代码语言:javascript复制
#登入 和没有权限的处理
[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/error/unauthorized.jsp
perms.unauthorizedUrl=/error/unauthorized.jsp
#用户密码和角色
[users]
tom=1234,admin
jack=123,manager
rose=000,oper
ami=123,admin,manager
#角色对应权限
[roles]
admin=*:*
manager=user:create,user:delete,user:select,leader:create,leader:delete,leader:select
oper=user:select,leader:select

[filters]
myroles=com.shiro.filter.MyRolesAuthorizationFilter
#请求对应角色
[urls]
/login=anon
/error/*=anon
/success=authc
/Department/*=myroles[admin,manager]
#roles[xx,xxx]这种写法是且的关系
/leader=roles[admin,manager]
/user=perms["user:create"]

最后就是写相关的jsp页面和服务端的处理业务,当然这里用到了前端的一些js和css需要引入,主要是jqeruy knockout bootstrap-table,此例子没有实现完整的CRUD功能,只是作为权限控制的了解。

比如登入代码:

代码语言:javascript复制
package com.shiro.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;

public class LoginServlet extends HttpServlet {
	public static String LOGIN_TYPE="login-in";

	private static final long serialVersionUID = 6164825538857134973L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		
		String username = request.getParameter("username");
		
		String password = request.getParameter("password");
		
		Subject subject = SecurityUtils.getSubject();
		
		AuthenticationToken token = new UsernamePasswordToken(username, password);
		
		try {
			subject.login(token);
			response.sendRedirect("success");
		} catch (AuthenticationException e) {
			if(StringUtils.hasText(type)&&LOGIN_TYPE.equals(type)){
				request.setAttribute("error", "用户名或密码错误!");
			}
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
//			e.printStackTrace();
		}
		
	}
}

登出:

代码语言:javascript复制
package com.shiro.servlet;

import java.io.IOException;

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 org.apache.shiro.SecurityUtils;
@WebServlet("/logout")
public class LoginoutServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		SecurityUtils.getSubject().logout();
		resp.sendRedirect("login");
	}
}

其中的一个简单业务:

代码语言:javascript复制
package com.shiro.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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 org.apache.commons.lang3.time.DateFormatUtils;

import com.shiro.entity.Department;

import net.sf.json.JSONArray;

@WebServlet("/Department/*")
public class DepartmentController extends HttpServlet{

	private static final long serialVersionUID = 4025943331108753214L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json,text/xml;charset=UTF-8");
		String uri = req.getRequestURI();
		if(uri.endsWith("/GetDepartment")){
			List<Department> depts = new ArrayList<Department>();
			buildDepts(depts);
//			ObjectMapper mapper = new ObjectMapper();
//	        mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
//	        String jsonStr = mapper.writeValueAsString(depts.get(0));
			JSONArray jsonArray = JSONArray.fromObject(depts);
			String json = "{"total":"   depts.size()   ","rows":"   jsonArray.toString()   "}"; 
	        PrintWriter out = resp.getWriter();
			out.write(json);
	        out.close();
		}else if(uri.endsWith("/SaveDepartment")){
			
		}
	}

	private void buildDepts(List<Department> depts) {
		for(int i=0;i<5;i  ){
			Department dept = new Department();
			dept.setId("" i);
			dept.setName("test" i);
			dept.setDes("这是test" i);
			dept.setLevel("" i);
			dept.setCreateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			depts.add(dept);
		}
	}
}

自定义的过滤器:

代码语言:javascript复制
package com.shiro.filter;


import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;


/**
 * Filter that allows access if the current user has the roles specified by the mapped value, or denies access
 * if the user does not have all of the roles specified.
 *
 * @since 0.9
 */
public class MyRolesAuthorizationFilter extends AuthorizationFilter {

    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }else{
        	for(String role:rolesArray){
        		if(subject.hasRole(role)){
        			return true;
        		}
        	}
        }
        
        return false;
    }

}

其余都是些请求-到页面的简单处理。

这个例子做的比较简单,没有完整的CRUD,只能大致了解请求的权限控制。

例子的代码https://github.com/suspring/shiro-web.git

0 人点赞