shiro安全框架

1.SsSM框架整合shiro(基于ssm框架环境无误的情况下)

  1.1.导入约束

<properties> <shiro.version>1.2.3</shiro.version> </properties> <!-- shiro --> <!-- shiro核心包 --> <!-- 添加shiro web支持 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <!-- 添加shiro spring整合 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.2.3</version> </dependency>

  1.2.在web.xml中配置过滤器

 <!-- shiro框架过滤器-->
    <filter>
        <filter-name>delegatingFilterProxy</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>delegatingFilterProxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

   1.3.配置spring的配置文件applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context   
                 http://www.springframework.org/schema/context/spring-context.xsd
                     http://www.springframework.org/schema/aop
                         http://www.springframework.org/schema/aop/spring-aop.xsd 
                          http://www.springframework.org/schema/tx
                               http://www.springframework.org/schema/tx/spring-tx.xsd">
    
 <!-- 第一步配置ShiroFilterFactoryBean-->
    <!-- 要求id跟web.xml配置的过滤器id一样-->
    <bean id="delegatingFilterProxy" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--登录页面-->
        <property name="loginUrl" value="/login.jsp"></property>
        <!--登录成功页面-->
        <property name="successUrl" value="/succes.jsp"></property>
        <!--无权限页面-->
        <property name="unauthorizedUrl" value="unauthorized.jsp"></property>
        <!--安全管理器-->
        <property name="securityManager" ref="SecurityManager"></property>
        <!-- 那些路径的访问权限-->
        <property name="filterChainDefinitions">
            <value>
                <!-- 按顺序赋予-->
                /login.jsp=anon <!-- anon无需认证-->
                /login/login=anon
                /chearuser=logout<!-- logout清除缓存-->
                /admin.jsp=roles[admin]<!-- 需要admin这个权限-->
                /user.jsp=roles[user]
                /**=authc<!-- 需要登录-->
            </value>
        </property>
        <!--<property name="filterChainDefinitionMap" ref="map">-->
        <!--</property>-->
    </bean>

 
<!-- 安全管理器-->
    <bean id="SecurityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--<property name="authenticator" ref="ModularRealmAuthenticatorr"/>-->
        <!-- 需要自定义一个Realm-->
        <property name="realm" ref="MyRealm"></property>
    </bean>


 <!--自定义一个Realm -->
    <bean id="MyRealm" class="cwd.Shiro.MyRealm">
        <!-- 加密证书匹配器-->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!-- 加密方法-->
                <property name="hashAlgorithmName" value="MD5"></property>
                <!-- 加密迭代的次数-->
                <property name="hashIterations" value="10"></property>
            </bean>
        </property>
    </bean>
   

</beans>

 

   1.4.自定义一个Realm类  

package cwd.Shiro;
import cwd.Pojo.PersonalPojo;
import cwd.Service.PersonalService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private PersonalService service;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //强转取得控制层传过来的UsernamePasswordToken
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //获取账号
        String zhanghao= token.getUsername();
        //获取realmname
        String realmname=getName();
        //加密的盐值
        ByteSource salt=ByteSource.Util.bytes(zhanghao);
        //根据账号去数据库查询
        PersonalPojo personal=service.findbyzhanghao(zhanghao);
        if (personal==null){
           throw new UnknownAccountException();
        }
        // 返回
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(zhanghao,personal.getMima(),salt,realmname);
        return simpleAuthenticationInfo;

    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取账号
        String  zhanghao= (String) principalCollection.getPrimaryPrincipal();
        PersonalPojo personal=service.findbyzhanghao(zhanghao);
        Set<String> roles=new HashSet<>();
        roles.add(personal.getQuanxian());
        if ("admin".equals(personal.getQuanxian())){
            roles.add("user");
        }
        //设置权限
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo(roles);
        return simpleAuthorizationInfo;
    }
}

 

   1.5.Controller处理登录

package cwd.Controller;

import cwd.Pojo.PersonalPojo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/login")
public class LoginController {
    @RequestMapping("/login")
    public String login(PersonalPojo pojo) {
        //获取subject对象
        Subject subject= SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            //封装一个UsernamePasswordToken对象
            UsernamePasswordToken token=new UsernamePasswordToken(pojo.getZhanghao(),pojo.getMima());
            //记住密码
            token.setRememberMe(true);
            //登录方法
                subject.login(token);
        }
        return "redirect:/succes.jsp";
    }
}

 

1.2加密

1.2.1在备注配置realm的bean的时候,添加加密方法

 <!--自定义一个Realm -->
    <bean id="MyRealm" class="cwd.Shiro.MyRealm">
        <!-- 加密证书匹配器-->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!-- 加密方法-->
                <property name="hashAlgorithmName" value="MD5"></property>
                <!-- 加密迭代的次数-->
                <property name="hashIterations" value="10"></property>
            </bean>
        </property>
    </bean>

 

1.2.2获取某数字的md5序列

 public static void main(String[] args) {
        //获取 123  MD5的 迭代10次的数列
       Object object=new SimpleHash("MD5","123",null,10);
        System.out.println(object);
    }

 

 1.2.3盐值加密,达到即使两个密码相同,序列也不一样

      String realmname=getName();
        //加密的盐值
        ByteSource salt=ByteSource.Util.bytes(zhanghao);
        //根据账号去数据库查询
        PersonalPojo personal=service.findbyzhanghao(zhanghao);
        if (personal==null){
           throw new UnknownAccountException();
        }
        // 返回
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(zhanghao,personal.getMima(),salt,realmname);

 

 1.3多realms验证

1.3.1配置多个reamls  bean 一个是md5加密 一个是sha1加密

 <bean id="MyRealm" class="cwd.Shiro.MyRealm">
        <!-- 加密证书匹配器-->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!-- 加密方法-->
                <property name="hashAlgorithmName" value="MD5"></property>
                <!-- 加密迭代的次数-->
                <property name="hashIterations" value="10"></property>
            </bean>
        </property>
    </bean>
    <bean id="MeRealm" class="cwd.Shiro.MeRealm">
        <!-- 加密-->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="SHA1"></property>
                <property name="hashIterations" value="10"></property>
            </bean>
        </property>
    </bean>

 

 1.3.2配置认证器

 <!-- 认证器-->
    <bean id="ModularRealmAuthenticatorr" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="realms">
            <list>
                <ref bean="MyRealm"></ref>
                <ref bean="MeRealm"></ref>
            </list>
        </property>
        <!-- 开启认证策略,都符合才通过,默认是一个通过就可以-->
        <property name="authenticationStrategy">
            <bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>
        </property>
    </bean>

 

 1.3.3注册认证器

 <!-- 安全管理器-->
    <bean id="SecurityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
   
       <!--注册认证器 -->
        <property name="authenticator" ref="ModularRealmAuthenticatorr"></property>
    </bean>

 

 

 

 

 

 

<!-- 安全管理器-->
<bean id="SecurityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--<property name="authenticator" ref="ModularRealmAuthenticatorr"/>-->
<!-- 需要自定义一个Realm-->
<property name="realm" ref="MyRealm"></property>
<property name="authenticator" ref="ModularRealmAuthenticatorr"></property>
</bean>
posted @ 2020-07-26 14:35  熬夜秃头选拨赛冠军  阅读(236)  评论(0编辑  收藏  举报