Apache Shiro 是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,受权,企业会话管理和加密。
Apache Shiro 的首要目标是易于使用和理解。安全有时候是很复杂的,甚至是痛苦的,但它没有必要这样。框架应该尽量掩盖复杂的地方,露出一个干净而直观的 API,来简化开发人员在使他们的应用程序安全上的努力。
如下是你能够用 Apache Shiro 所作的事情:
验证用户来核实他们的身份
对用户执行访问控制,如:
判断用户是否被分配了一个肯定的安全角色。
判断用户是否被容许作某事。
在任何环境下使用 Session API,即便没有 Web 或 EJB 容器。
在身份验证,访问控制期间或在会话的生命周期,对事件做出反应。
汇集一个或多个用户安全数据的数据源,并做为一个单一的复合用户“视图”。css
启用单点登陆(SSO)功能。html
并发登陆管理(一个帐号多人登陆做踢人操做)。java
为没有关联到登陆的用户启用"Remember Me"服务。
…web
以及更多——所有集成到紧密结合的易于使用的 API 中。spring
目前Java领域主流的安全框架有SpringSecurity和Shiro,相比于SpringSecurity,Shiro轻量化,简单容易上手,且不局限于Java和Spring;SpringSecurity太笨重了,难以上手,且只能在Spring里用,因此博主极力推荐Shiro。apache
spring集成shiro要用到shiro-all-1.2.4.jarspring-mvc
jar包下载地址:http://download.csdn.net/detail/qq_33556185/9540257安全
第一步:配置shiro.xml文件并发
shiro.xml配置文件代码:mvc
- <?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">
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <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=authc,perms[/userList]
- /toDeleteUser=authc,perms[/toDeleteUser]
- /** = authc
- </value>
- </property>
- </bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="myRealm" />
- </bean>
-
- <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;
-
-
- 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());
- }
- }
- }
-
-
- 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();
-
- 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 currentUser = SecurityUtils.getSubject();
-
- String salt="("+request.getParameter("username")+")";
- String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();
-
- 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的认证及受权便完成了。
http://blog.csdn.net/qq_33556185/article/details/51579680