shiro de inicio rápido (a)

El control de acceso

La manera más común

  • intercepción url
    • El cliente envía una solicitud al servidor para interceptar, seguido por el control de acceso
  • método de notas
    • capa del controlador para crear un objeto proxy, los permisos de objetos proxy de comprobar

funcionalidad principal shiro

  1. Autenticar
  2. Autorizar
  3. Administración de sesiones
  4. encriptación

Proceso de certificación

llamada applicationcode- -> Llamada de sujeto--> seguridad llamada gerente- -> reino

  1. applicationcode (código de aplicación)
  2. sujeto (en nombre del usuario actual)
  3. Security Manager (Administrador de seguridad)
  4. reino (DAO similares, para el acceso a los datos)

En combinación con la web

  • Configuración de filtros
<!-- 配置shiro过滤器 -->
<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>
  • Configuración en la primavera
<?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-4.3.xsd">

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <property name="successUrl" value="/index.html"/>
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>

        <!--
            filterChainDefinitions
            配置规则:
                先配置的优先,会覆盖后配置的
                配置url拦截拦截器:url = 拦截器
            过滤器类型
                1. anon(AnonymousFilter.class):可匿名访问
                2. authc(FormAuthenticationFilter.class):需认证
                3. authcBasic(BasicHttpAuthenticationFilter.class)
                4. logout(LogoutFilter.class):登出
                5. noSessionCreation(NoSessionCreationFilter.class):
                6. perms(PermissionsAuthorizationFilter.class):
                7. port(PortFilter.class):
                8. rest(HttpMethodPermissionFilter.class):
                9. roles(RolesAuthorizationFilter.class):角色权限
                    url = roles[user]
                10. ssl(SslFilter.class):
                    url =
                11. user(UserFilter.class):
        -->
        <!--
            1. 方式一:直接配置键值对
        <property name="filterChainDefinitions">
            <value>
                /login = anon
                /checkLogin = anon
                /logout = logout
                # /user/list = roles[admin]
                /** = authc
            </value>
        </property>
        -->
        <!--
            2. 方式二:配置一个map,从数据库中获取拦截信息
        -->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap" />
    </bean>
    
    <!-- 从工厂获取实例filterChainDefinitionMap,用于装配到url权限拦截属性中 -->
    <bean id="filterChainDefinitionMap"
          factory-bean="filterChainDefinitionMapFactory"
          factory-method="getFilterChainDefinitionMap"/>
    <!-- 配置实例工厂,用于生产filterChainDefinitionMap -->
    <bean id="filterChainDefinitionMapFactory" class="com.blog.shiro.FilterChainDefinitionMapFactory"/>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="blogRealm"></property>
        <!-- 配置多realm认证 -->
        <!--<property name="authenticator" ref="authenticator"/>-->
    </bean>

    <!--
    配置多realm认证器
    也可直接将多个realm注入securityManager的realm属性,shiro会自动将其转换为ModularRealmAuthenticator
    -->
    <!--<bean name="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="realms">
            <list>
                <ref bean="blogRealm"/>
                <ref bean="secondRealm"/>
            </list>
        </property>
        &lt;!&ndash;
        配置认证器认证策略
        1. 有一个通过认证即可(默认)
        2. 需全部通过认证 AllSuccessfulStrategy
        &ndash;&gt;
        <property name="authenticationStrategy">
            <bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>
        </property>
    </bean>-->

    <bean id="blogRealm" class="com.blog.shiro.BlogRealm">
        <!-- credentialsMatcher:shiro的密码比对器 -->
        <!--<property name="credentialsMatcher">
            &lt;!&ndash;
            配置加密: HashedCredentialsMatcher
                hashAlgorithmName:加密的算法
                hashIterations:加密的次数
            &ndash;&gt;
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"/>
                <property name="hashIterations" value="10"/>
            </bean>
        </property>-->
    </bean>

    <!-- 第二个realm:需要时关闭注释 -->
    <!--<bean id="secondRealm" class="com.blog.shiro.SecondRealm">
        &lt;!&ndash; credentialsMatcher:shiro的密码比对器 &ndash;&gt;
        <property name="credentialsMatcher">
            &lt;!&ndash;
            配置加密: HashedCredentialsMatcher
                hashAlgorithmName:加密的算法
                hashIterations:加密的次数
            &ndash;&gt;
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="SHA1"/>
                <property name="hashIterations" value="10"/>
            </bean>
        </property>
    </bean>-->

    <!-- shiro开启注解方法权限控制 -->
    <bean name="defaultAdvisorAutoProxyCreator"
          class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
        <!--
            proxyTargetClass
                true:使用cglib代理
                false:使用jdk动态代理
        -->
        <property name="proxyTargetClass" value="true"/>
    </bean>
    <!-- 配置shiro提供的切面类,用于创建代理对象 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
</beans>
  • Realm configuración Clase
public class BlogRealm extends AuthorizingRealm {

    @Resource
    UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //TODO 从数据库获取获取前用户权限并进行授权
        //1. 从principalCollection中获取的登录用户信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        //2. 利用登录信息在数据库中查询权限或角色,未写出
        if(user.getName().equals("admin"))
        //3. 进行授权
            simpleAuthorizationInfo.addRole("admin");
        return simpleAuthorizationInfo;
    }

    /**
     * 认证方法,可用于登录
     * @return 一个认证对象,若为null则表示认证不通过
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证");
        //根据用户名在数据库中查询密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String userName = usernamePasswordToken.getUsername();
        User user = userDao.getUserByName(userName);
        //用户不存在,则return null
        if (user == null) {
            return null;
        }
        //盐值
        //ByteSource credentialsSalt = ByteSource.Util.bytes(userName) ;
        //框架将密码与输入进行比对
        //构建一个简单的认证对象,后由 securityManager 调用认证器
        //1. 不加盐
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        //2. 加盐 SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) i
        //AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,this.getName());
        return authenticationInfo;
    }
}
  • invalidez Shiro combina comentario acceso SpringMVC
    • Si SpringMVC y de shiro perfil no se fusionan, es necesario configurar en el SpringMVC

    <Aop: config proxy-target-class = “true” />

  1. Obtener url para interceptar información de la base de datos
  • clase de fábrica
public class FilterChainDefinitionMapFactory {

    public HashMap<String, String> getFilterChainDefinitionMap() {

        HashMap<String, String> filterChainDefinitionMap = new HashMap<>();
        //TODO 从数据库中查询获得拦截url与权限对
        //需注意顺序,优先匹配
        filterChainDefinitionMap.put("/checkLogin", "anon");
        filterChainDefinitionMap.put("/**", "authc");

        return filterChainDefinitionMap;
    }
}
Publicado 17 artículos originales · ganado elogios 1 · visitas 657

Supongo que te gusta

Origin blog.csdn.net/c_c_y_CC/article/details/88769150
Recomendado
Clasificación