Apache Shiro 的首要目标是易于使用和理解。安全有时候是很复杂的,甚至是痛苦的,但它没有必要这样。框架应该尽可能掩盖复杂的地方,露出一个干净而直观的 API,来简化开发人员在使他们的应用程序安全上的努力。
以下是你可以用 Apache Shiro 所做的事情:
验证用户来核实他们的身份
对用户执行访问控制,如:
判断用户是否被分配了一个确定的安全角色。
判断用户是否被允许做某事。
在任何环境下使用 Session API,即使没有 Web 或 EJB 容器。
在身份验证,访问控制期间或在会话的生命周期,对事件作出反应。
聚集一个或多个用户安全数据的数据源,并作为一个单一的复合用户“视图”。
启用单点登录(SSO)功能。
并发登录管理(一个账号多人登录作踢人操作)。
…
以及更多——全部集成到紧密结合的易于使用的 API 中。
目前Java领域主流的安全框架有SpringSecurity和Shiro,相比于SpringSecurity,Shiro轻量化,简单容易上手,且不局限于Java和Spring;SpringSecurity太笨重了,难以上手,且只能在Spring里用,所以博主极力推荐Shiro。
spring集成shiro要用到shiro-all-1.2.4.jar
jar包下载地址:http://download.csdn.net/detail/qq_33556185/9540257
第一步:配置shiro.xml文件
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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- Shiro Filter 拦截器相关配置 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- securityManager -->
<property name="securityManager" ref="securityManager" />
<!-- 登录路径 -->
<property name="loginUrl" value="/toLogin" />
<!-- 用户访问无权限的链接时跳转此页面 -->
<property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />
<!-- 过滤链定义 -->
<property name="filterChainDefinitions">
<value>
/loginin=anon
/toLogin=anon
/css/**=anon
/html/**=anon
/images/**=anon
/js/**=anon
/upload/**=anon
<!-- /userList=roles[admin] -->
/userList=authc,perms[/userList]
/toDeleteUser=authc,perms[/toDeleteUser]
/** = authc
</value>
</property>
</bean>
<!-- securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
</bean>
<!-- 自定义Realm实现 -->
<bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
anno代表不需要授权即可访问,对于静态资源,访问权限都设置为anno
authc表示需要登录才可访问
/userList=roles[admin]的含义是要访问/userList需要有admin这个角色,如果没有此角色访问此URL会返回无授权页面
/userList=authc,perms[/userList]的含义是要访问/userList需要有/userList的权限,要是没分配此权限访问此URL会返回无授权页面
<bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />
这个是业务对象,需要我们去实现。第二步:在web.xml文件里加载shiro.xml,和加载其他配置文件是一样的,就不多说了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/spring/spring-common.xml,
classpath*:/spring/shiro.xml
</param-value>
</context-param>
第三步:配置shiroFilter,所有请求都要先进shiro的代理类
<!--
DelegatingFilterProxy类是一个代理类,所有的请求都会首先发到这个filter代理
然后再按照"filter-name"委派到spring中的这个bean。
在Spring中配置的bean的name要和web.xml中的<filter-name>一样.
targetFilterLifecycle,是否由spring来管理bean的生命周期,设置为true有个好处,可以调用spring后续的bean
-->
<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>
第四步:自定义realm
package com.core.shiro.realm;
import java.util.List;
import javax.annotation.Resource;
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.authc.UsernamePasswordToken;
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.springframework.util.StringUtils;
import com.core.shiro.dao.IPermissionDao;
import com.core.shiro.dao.IRoleDao;
import com.core.shiro.dao.IUserDao;
import com.core.shiro.entity.Permission;
import com.core.shiro.entity.Role;
import com.core.shiro.entity.User;
public class CustomRealm extends AuthorizingRealm{
@Resource
private IUserDao userDao;
@Resource
private IPermissionDao permissionDao;
@Resource
private IRoleDao roleDao;
/**
* 添加角色
* @param username
* @param info
*/
private void addRole(String username, SimpleAuthorizationInfo info) {
List<Role> roles = roleDao.findByUser(username);
if(roles!=null&&roles.size()>0){
for (Role role : roles) {
info.addRole(role.getRoleName());
}
}
}
/**
* 添加权限
* @param username
* @param info
* @return
*/
private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) {
List<Permission> permissions = permissionDao.findPermissionByName(username);
for (Permission permission : permissions) {
info.addStringPermission(permission.getUrl());//添加权限
}
return info;
}
/**
* 获取授权信息
*/
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//用户名
String username = (String) principals.fromRealm(getName()).iterator().next();
//根据用户名来添加相应的权限和角色
if(!StringUtils.isEmpty(username)){
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
addPermission(username,info);
addRole(username, info);
return info;
}
return null;
}
/**
* 登录验证
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {
//令牌——基于用户名和密码的令牌
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//令牌中可以取出用户名
String accountName = token.getUsername();
//让shiro框架去验证账号密码
if(!StringUtils.isEmpty(accountName)){
User user = userDao.findUser(accountName);
if(user != null){
return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
}
}
return null;
}
}
第五步:控制层代码
package com.core.shiro.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ShiroAction {
@RequestMapping("loginin")
public String login(HttpServletRequest request){
//当前Subject
Subject currentUser = SecurityUtils.getSubject();
//加密(md5+盐),返回一个32位的字符串小写
String salt="("+request.getParameter("username")+")";
String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();
//传递token给shiro的realm
UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("username"),md5Pwd);
try {
currentUser.login(token);
return "welcome";
} catch (AuthenticationException e) {//登录失败
request.setAttribute("msg", "用户名和密码错误");
}
return "login";
}
@RequestMapping("toLogin")
public String toLogin(){
return "login";
}
}
第六步:login页面 略
login请求调用currentUser.login之后,shiro会将token传递给自定义realm,此时realm会先调用doGetAuthenticationInfo(AuthenticationToken authcToken )登录验证的方法,验证通过后会接着调用 doGetAuthorizationInfo(PrincipalCollection principals)获取角色和权限的方法(授权),最后返回视图。
当其他请求进入shiro时,shiro会调用doGetAuthorizationInfo(PrincipalCollection principals)去获取授权信息,若是没有权限或角色,会跳转到未授权页面,若有权限或角色,shiro会放行,ok,此时进入真正的请求方法……
到此shiro的认证及授权便完成了。