Spring MVC 急速集成 Shiro

     相信有很多的程序员,不愿意进行用户管理这块代码实现。

     原因之一,不同的JavaEE 系统,用户管理都会有个性化的实现,逻辑很繁琐。

     而且是系统门面,以后背锅的几率非常大,可谓是低收益高风险。

     最近在系统中集成了 Shiro,感觉这个小家伙还是相当灵活的。

     完善的用户认证和授权,干净的API,让人如沐春分。

     本文重点描述集成过程,能让你迅速的将 Shiro 集成到 JavaEE 项目中,毕竟项目都挺紧张的。

     至于其中的源码的实现,可以找个闲暇的夜晚,细细品味。

1.前戏

    Shiro 核心jar:

    JavaEE 应用开始的地方,web.xml 配置:

复制代码
         <filter> 
           <filter-name>shiroFilter</filter-name> 
           <filter-class> 
              org.springframework.web.filter.DelegatingFilterProxy 
           </filter-class> 
         </filter> 
         <filter-mapping> 
           <filter-name>shiroFilter</filter-name> 
           <url-pattern>/*</url-pattern> 
         </filter-mapping>
复制代码

   Shiro Spring 注解文件,应用启动的使用,会帮助你做很多事情:

复制代码
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!-- 数据库保存的密码是使用MD5算法加密的,所以这里需要配置一个密码匹配对象 -->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"/>
    <!-- 缓存管理 -->
    <!--<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>-->
    <!--
      使用Shiro自带的JdbcRealm类
      指定密码匹配所需要用到的加密对象
      指定存储用户、角色、权限许可的数据源及相关查询语句
     -->
    <bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
        <property name="permissionsLookupEnabled" value="true"/>
        <property name="dataSource" ref="basedb"/>
        <property name="authenticationQuery" value="SELECT NSRMC FROM USER WHERE USERID = ?"/>
        <!--<property name="userRolesQuery" value="SELECT role_name from sec_user_role left join sec_role using(role_id) left join sec_user using(user_id) WHERE user_name = ?"/>-->
        <!--<property name="permissionsQuery" value="SELECT permission_name FROM sec_role_permission left join sec_role using(role_id) left join sec_permission using(permission_id) WHERE role_name = ?"/>-->
    </bean>
    <!--自定义认证-->
    <bean id="myRealm" class="cn.orson.common.MyRealm"/>

    <!-- Shiro安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--多realms配置-->
        <property name="realms">
            <list>
                <ref bean="myRealm"/>
                <ref bean="jdbcRealm"/>
            </list>
        </property>
        <!--<property name="realm" ref="jdbcRealm"/>-->
        <!--<property name="cacheManager" ref="cacheManager"/>-->
    </bean>

    <!--
       Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行
       Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持
    -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码) -->
        <!-- <property name="successUrl" value="/" ></property> -->
        <!-- 用户访问未对其授权的资源时,所显示的连接 -->
        <property name="unauthorizedUrl" value="/"/>
        <property name="filterChainDefinitions">
            <value>
                /security/*=anon
                /tag=authc
            </value>
        </property>
    </bean>
    <bean id="shiroLogin" class="cn.orson.common.ShiroLogin"/>
    <!--
       开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,
       并在必要时进行安全逻辑验证
    -->
    <!--
    <bean
        class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
    <bean
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"></property>
    </bean>
    -->
</beans>
复制代码

2.个性化

   请求发起的地方一般是前端,不管你是 .jsp/.php/.net.......方式都是类似

复制代码
<html>
<body>
<h1>login page</h1>
<form id="" action="service/dologin" method="post">
    <label>账号:</label><input name="userName" maxLength="40"/>
    <input title="是否是管理员" type="checkbox" name="isAdmin"><label>是否为管理员</label><br>
    <label>密码:</label><input title="密码" type="password" name="password" /><br>
    <input type="submit" value="登录"/>
</form>
<%--用于输入后台返回的验证错误信息 --%>
<P><c:out value="${message }"/></P>
</body>
</html>
复制代码

   项目中肯定需要自定义项目验证域

复制代码
public class MyRealm extends AuthorizingRealm {
    Log log = LogFactory.getLog(MyRealm.class);
    /**
     * 为当前登录的Subject授予角色和权限
     * 经测试:本例中该方法的调用时机为需授权资源被访问时
     * 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
     * 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache
     * 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        log.info("-----------------access doGetAuthorizationInfo----------------------");
        //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
        String currentUsername = (String)super.getAvailablePrincipal(principals);
// 这里实现自己的业务逻辑 // 根据业务逻辑,设置角色和权限
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); //实际中可能会像上面注释的那样从数据库取得 if(null!=currentUsername && "mike".equals(currentUsername)){ //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色 simpleAuthorInfo.addRole("admin"); simpleAuthorInfo.addStringPermission("admin:manage"); //添加权限return simpleAuthorInfo; } //若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址 //详见applicationContext.xml中的<bean id="shiroFilter">的配置 return null; } /** * 验证当前登录的Subject * 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {//获取基于用户名和密码的令牌 //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的 //两个token的引用都是一样的 UsernamePasswordToken token = (UsernamePasswordToken)authcToken; log.info("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息 //说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了) //这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证 /* if("mike".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("mike", "mike", this.getName()); authcInfo.getCredentials(); this.setSession("currentUser", "mike"); return authcInfo; }*///没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常 return null; } /** * 将一些数据放到ShiroSession中,以便于其它地方使用 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession();if(null != session){ session.setAttribute(key, value); } } } }
复制代码

    请求的后台服务,在这里你可以在进行一点业务逻辑

复制代码
@Controller
@RequestMapping(value = "/")
public class ShiroLogin {
    /**
     * 实际的登录代码
     * 如果登录成功,跳转至首页;登录失败,则将失败信息反馈对用户
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "dologin",method = RequestMethod.POST)
    @ResponseBody
    public String doLogin(HttpServletRequest request, Model model) {
        String msg = "";
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

/*UsernamePasswordToken token = new UsernamePasswordToken(userName, password); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); if (subject.isAuthenticated()) { return "redirect:/"; } else { return "login"; } } catch (IncorrectCredentialsException e) { msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect."; model.addAttribute("message", msg); System.out.println(msg); } catch (ExcessiveAttemptsException e) { msg = "登录失败次数过多"; model.addAttribute("message", msg); System.out.println(msg); } catch (LockedAccountException e) { msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked."; model.addAttribute("message", msg); System.out.println(msg); } catch (DisabledAccountException e) { msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled."; model.addAttribute("message", msg); System.out.println(msg); } catch (ExpiredCredentialsException e) { msg = "帐号已过期. the account for username " + token.getPrincipal() + " was expired."; model.addAttribute("message", msg); System.out.println(msg); } catch (UnknownAccountException e) { msg = "帐号不存在. There is no user with username of " + token.getPrincipal(); model.addAttribute("message", msg); System.out.println(msg); } catch (UnauthorizedException e) { msg = "您没有得到相应的授权!" + e.getMessage(); model.addAttribute("message", msg); System.out.println(msg); }*/ } }
复制代码

     整个集成工作就结束了,是不是简单的不要不要的。

     等下次项目经理指派你做用户管理的时候,只需要花半天的时间做设计。

     借助Shiro 半天时间实现代码。

     然后将剩下的时间,做做自己喜欢的其他研究工作

猜你喜欢

转载自blog.csdn.net/wushuchu/article/details/51819168