zoukankan      html  css  js  c++  java
  • Shiro在SSM框架中的应用

    上一篇Shiro基础的连接 

     如果想使用Relam的操作,那么必须要保证有一个具体的认证类实现了Relam接口

    web.xml增加shiro的配置

        <!-- 进行shiro的过滤器的配置 -->
        <filter>
            <filter-name>shiroFilter</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
            <!-- 该参数表示shiro的生命周期将交由Spring容器进行管理(默认情况下,取值为false) -->
            <!-- 如果将其内容设置为true,则表示由Servlet容器进行管理 -->
            <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>
        <welcome-file-list>
            <welcome-file>login.jsp</welcome-file>
        </welcome-file-list>

    在applicationContext.xml加入shiro配置项信息

    配置shiro的登录入口

        <!-- 此处表示使用内置的表单登录控制验证 -->
        <bean id="formAuthenticationFilter" class="com.sk.shiro.MyFormAuthenticationFilter">
            <!-- 定义出需要使用的参数,此参数与表单一一对应 -->
            <property name="usernameParam" value="username"/>
            <property name="passwordParam" value="password"/>
            <!-- <property name="loginUrl" value="/login.jsp"/> 不用配置 默认是这个 -->
        </bean>  

        配置Shiro过滤器

        <!-- 配置shiro过滤器 -->
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <!-- 表示现在要配置的是一个安全管理器 -->
            <property name="securityManager" ref="securityManager"/>
            <!-- 登录成功之后的跳转访问路径 -->
            <property name="successUrl" value="/index.jsp"/>
            <!-- 配置shiro里面需要使用到的过滤器操作 -->
            <property name="filters">
                <map>
                    <entry key="authc" value-ref="formAuthenticationFilter"/>
                </map>
            </property> 
    
            <!-- shiro里面需要针对于所有的路径进行配置,所有的配置需要通过文本的形式设置 -->
            <property name="filterChainDefinitions">
                <value>
                    /login.jsp=authc<!--loginUrl 需要和loginUrl一致  -->
                    /successUrl=authc
                     /test/*=user 
                    /test*=user  
                </value>
            </property>
        </bean> 

       配置SecurityManager管理器

        <!-- 配置SecurityManager的管理 -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <!-- 配置你需要使用的Realms -->
            <property name="realms">
                <list>
                    <ref bean="usernamePasswordRealm"/>
                </list>
            </property>
            <!-- 定义要使用的session管理器 -->
            <property name="sessionManager" ref="sessionManager"/>
        </bean>

    编写UsernamePasswordRealm进行认证授权

    package com.sk.shiro;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.authc.UnknownAccountException;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    
    public class UsernamePasswordRealm extends AuthorizingRealm {
        
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            System.out.println("********** 2、用户角色与权限:doGetAuthorizationInfo **********");
            String username = (String) principals.getPrimaryPrincipal() ;    // 取得用户登录名
            SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ;    // 定义授权信息的返回数据
            try {
                Set<String> allRoles = new HashSet<>();
                allRoles.add("admin");
                Set<String> allActions =  new HashSet<>();
                auth.setRoles(allRoles);// 所有的角色必须以Set集合的形式出现
                auth.setStringPermissions(allActions);     // 所有的权限必须以Set集合的形式出现
            } catch (Exception e) {
                e.printStackTrace(); 
            } 
            return auth;
        }
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
            System.out.println("********** 1、用户登录认证:doGetAuthenticationInfo() **********");
            // 1、登录认证的方法需要先执行,需要用他来判断登录的用户信息是否合法
            String username = (String) token.getPrincipal() ;    // 取得用户名
            if(!"admin".equals(username)) {
                throw new UnknownAccountException("用户名不存在");
            }
            // 需要通过用户名取得用户的完整信息,利用业务层操作
            String password = (String) token.getCredentials();
            System.err.println("密码"+password);
            AuthenticationInfo auth = new SimpleAuthenticationInfo(username, password, "myRealm") ;
            return auth ;
        } 
        @Override
        public boolean supports(AuthenticationToken token) {
            MyAuthenticationToken t=null;
            try {
                 t = (MyAuthenticationToken) token;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return t.getLoginType() == LoginType.USERNAME_PASSWORD;
        }
    }
    View Code
    这是首页登录的jsp
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"//"+request.getServerName()+":"+request.getServerPort();
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <%-- <base href="<%=basePath %>"> --%>
    <%System.out.println("---"+basePath); %>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Shiro</title>
    </head>
    <body>
        <form action="/login.jsp" method = "post">
        用户名<input type="text" name = "username" id = "username"><br>
        密码 <input type="password" name = "password" id = "password"><br>
        <input type="hidden" name = "loginType" value = "USERNAME_PASSWORD">
        <input type="submit" value="登录">
        <input type="reset" value="重置">
        </form>
    </body>
    </html>

    shiro登录的流程

    从登陆的jsp的action找到配置的formAuthenticationFilter(此接口中有createToken等方法 根据登陆方式可以使用自定义token 实现HostAuthenticationToken, RememberMeAuthenticationToken接口 可以自定义token )

    然后登录的路径被shiroFilter过滤

    shiroFilter交给配置的securityManager去管理

    securityManager又交给配置的usernamePasswordRealm去授权和认证(supports()方法返回true代表使用这个Realm去认证 此处为了兼容多种登陆方式 比如手机验证码、用户名密码 等)

    登录成功之后的跳转访问路径 

    <property name="successUrl" value="/index.jsp"/>

    下一篇会写在集群环境下Shiro的Session管理

  • 相关阅读:
    推荐几款Winform下的皮肤控件!
    PetShop之业务逻辑层设计 《解剖PetShop》系列之五
    25款.NET开发必备工具推荐
    在aspx页面实现高亮显示搜过关键字
    PetShop之ASP.NET缓存 《解剖PetShop》系列之四
    ASP.NET页面加载顺序
    PetShop之表示层设计 《解剖PetShop》系列之六
    C#打包应用程序
    .NET获取英文月份缩写名(可获取其他国家)
    SQL Server 日期格式化输出
  • 原文地址:https://www.cnblogs.com/ssskkk/p/9278925.html
Copyright © 2011-2022 走看看