本文主要是介绍Shiro的两种配置方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Apache Shiro是一款Java 安全框架,可以用于完成认证、授权、加密、会话管理、与Web集成、缓存等功能。根据官方文档,我这里列举出两种常用的配置方式,一是ini文件配置,二是spring xml文件的配置方式。
二者的配置,基本都是针对Shiro的以下几个常用组件:securityManager,cachManager,Realm,以及对应的链接拦截规则(urls)。
1. shiro.ini文件配置方式
我所用的是IDEA环境,在resources目录下新建config目录,用于存放相关配置文件,这里的Shiro.ini 文件也放在下面。你也可以放在你自己的目录,只不过要在web.xml指明配置文件的路径(默认为classpath下shiro.ini文件)。
shiro.ini文件的基本内容:这里的[urls]下anon代表对应链接不需要用户登录以及权限即可访问,authc代表需要用户登录才可以访问,其他标签可查看官方文档,在之后的学习过程中,根据实例再续写。
[main]
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManagermyShiroRealm = com.song.shiro.realm.MyRealm
myShiroRealm.cacheManager = $cacheManagersecurityManager.realm = $myShiroRealmsecurityManager.rememberMeManager.cipherKey=falseshiro.loginUrl = /admin/login
shiro.successUrl = /admin/success[urls]
/admin/login = anon
/admin/success = authc
/other/index = authc
/logout = logout
对应地,在web.xml中配置文件加载监听器及对应的Shiro拦截器配置为:
<context-param><param-name>shiroConfigLocations</param-name><param-value>classpath:config/shiro.ini</param-value></context-param><listener><listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class></listener><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><dispatcher>REQUEST</dispatcher><dispatcher>FORWARD</dispatcher><dispatcher>INCLUDE</dispatcher><dispatcher>ERROR</dispatcher></filter-mapping>
2. spring xml文件配置方式:
spring-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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"default-lazy-init="true"><description>Shiro Configuration</description><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager"/><property name="loginUrl" value="/admin/index" /><property name="successUrl" value="/admin/success" /><property name="unauthorizedUrl" value="/error" /><property name="filterChainDefinitions"><value>/admin/login = anon/admin/success = authc/other/index = authc/logout = logout/** = anon</value></property></bean><!-- 用户授权信息Cache --><bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="myRealm"/><property name="cacheManager" ref="cacheManager" /></bean><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/><!-- Define the Shiro Realm implementation you want to use to connect to your back-end --><!-- security datasource: --><bean id="myRealm" class="com.song.shiro.realm.MyRealm"><property name="cacheManager" ref="cacheManager" /></bean><!-- Enable Shiro Annotations for Spring-configured beans. Only run after --><!-- the lifecycleBeanProcessor has run: --><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></beans>
对应地,web.xml中加载监听器以及Shiro过滤器的配置如下:
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:config/applicationContext.xml,classpath:config/spring-shiro1.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><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><dispatcher>REQUEST</dispatcher><dispatcher>FORWARD</dispatcher><dispatcher>INCLUDE</dispatcher><dispatcher>ERROR</dispatcher></filter-mapping>
3. 说明
以上两种方式给出的配置,一般来说,对于实际web工程,只需要改动ini中的[urls]部分或者spring-xml中的shiroFilter配置部分。即定义web资源对应的操作控制权限。具体的语法以及分类,在接下来的具体实践中,再根据实例说明。
另外,配置文件中关于Realm的配置中时使用的MyRealm,这个是自己写的Realm,用于提供用户名称密码、角色、权限等封装信息的接口,以下是测试用例中的具体的实现(来源于网络,测试通过),其具体调用系统调用Shiro用户登录接口(subject.login(user))时触发:
/*** Created by Song on 2016/12/27.*/
public class MyRealm extends AuthorizingRealm {//这里因为没有调用后台,直接默认只有一个用户("spf","123456")private static final String USER_NAME = "spf";private static final String PASSWORD = "123456";@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {Set<String> roleNames = new HashSet<String>();Set<String> permissions = new HashSet<String>();roleNames.add("admin");//添加角色permissions.add("read"); //添加权限SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);info.setStringPermissions(permissions);return info;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;if(token.getUsername().equals(USER_NAME)){return new SimpleAuthenticationInfo(USER_NAME, MD5Util.MD5(PASSWORD), getName());}else{throw new AuthenticationException();}}
}
测试中用到的login.jsp页面(登录框):这里直接通过action提交表单,便于后台直接跳转页面,当然你也可以采用js Ajax提交请求,这样的话,就只能通过js根据返回的数据体进行页面跳转。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head><script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form action="<%=request.getContextPath()%>/admin/checkLogin"><input type="text" name="username" ><br><br><input type="password" name="password"><br><br><input type="checkbox" name="rememberMe" value="true"/>Remember Me?<br><button type="submit" id="loginbtn">登录</button>
</form>
</body>
对应的/admin/checkLogin用户登录验证代码如下:
/*** 验证用户名和密码* @param username,String password* @return*/@RequestMapping(value="/checkLogin")public String checkLogin(String username, String password, ServletRequest request) {Map<String, Object> result = new HashMap<String, Object>();try{UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Util.MD5(password));Subject currentUser = SecurityUtils.getSubject();if (!currentUser.isAuthenticated()){//使用shiro来验证token.setRememberMe(true);currentUser.login(token);//验证角色和权限//获取本来要访问的网址uriString uri = WebUtils.getSavedRequest(request).getRequestUrl();//去掉工程名shirosif(uri.split("/shiros").length>1)return "redirect:"+uri.split("/shiros")[1];}}catch(Exception e){e.printStackTrace();}return "redirect:/admin/success";}
这篇关于Shiro的两种配置方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!