SpringMVC和Shiro 整合

一.Pom配置文件

<properties>
    <shiro.version>1.2.2</shiro.version>
</properties>

<!--shiro start-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>${shiro.version}</version>
</dependency>

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-quartz</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>${shiro.version}</version>
</dependency>
<!--shiro end-->

 二.shiro 配置文件。

 2.1 添加spring-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util" 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
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <description> shiro 配置</description>

    <!--1,配置SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

    </bean>
    <!--2.配置cacheManager-->
    <bean class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>

    <!--3.配置authenticator-->
    <bean class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="authenticationStrategy">
            <bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"></bean>
        </property>
    </bean>

    <!--4.配置realm -->
    <bean class="com.gitub.xl137010393.realm.ShiroRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"></property>
                <property name="hashIterations" value="1024"></property>
            </bean>
        </property>
    </bean>
    <!--5.配置lifecycleBeanPostProcessor 可以自动的来调用配置在Spring IOC 容器中的生命周期方法-->
   <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
    <!--6.启动IOC容器中使用shiro 的注解,但必须配置lifecycleBeanPostProcessor 之后,才能使用-->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"></bean>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"></property>
    </bean>

    <!--配置shiroFilter-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <property name="loginUrl" value="/login.jsp"></property>
        <!--这里直接用Controller里面跳转到成功界面,所以没设置参数-->
        <property name="successUrl" value="/"></property>
        <property name="unauthorizedUrl" value="/"></property>
        <!-- 配置哪些页面需要受保护. 以及访问这些页面需要的权限.
       1). anon(anonymous) 可以被匿名访问 2). authc(authentication)
       必须认证(即登录)后才可能访问的页面. 3). logout 登出.4)等等其他的,没用到 我就不写出来了 -->
        <property name="filterChainDefinitions">
            <value>
                /login.jsp=anon
                /login=anon
                #表示其他所有的url都需要认证
                /** =authc
            </value>
        </property>
    </bean>
</beans>

2.2 在web.xml 配置

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring-*.xml</param-value>
</context-param>
<!--shiro filter  过滤器-->
<filter>
  <description>权限拦截</description>
  <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>

3.relam

package com.gitub.xl137010393.realm;


import org.apache.shiro.authc.*;
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.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    /***
     * 授权
     * @param
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object principal = principals.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if ("admin".equals(principal.toString())) {
            roles.add("admin");
            info.setRoles(roles);
            info.addStringPermissions(Arrays.asList("admin:*"));
        } else if ("user".equals(principal.toString())) {
            roles.add("user");
            info.setRoles(roles);
            info.addStringPermissions(Arrays.asList("user:*"));
        }
        return info;
    }

    /****
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String principal = username;
        String credentials = "";

        if ("admin".equalsIgnoreCase(username)){
            credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
        }else if ("user".equalsIgnoreCase(username)){
            credentials ="";
        }
        String realmName = getName();
        ByteSource salt = ByteSource.Util.bytes(username);
        SimpleAuthenticationInfo info = null;
        info = new SimpleAuthenticationInfo(principal,credentials,salt,realmName);
        return info;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38233650/article/details/89329386