shiro实现认证

2019-10-06  本文已影响0人  ssttIsme

pom.xml

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.3.2</version>
        </dependency>

核心代码

        String password = entity.getPassword();
        if(!StringUtils.isEmpty(password)){
            //将用户输入的密码转换为ByteSource对象
            ByteSource source = ByteSource.Util.bytes(password.getBytes());
            //创建一个随机盐值(采用盐值加密会更加安全)
            String salt=UUID.randomUUID().toString();
            //对密码和盐值进行统一加密,产生一个密文对象
            SimpleHash simpleHash = new SimpleHash("MD5",source,salt);
            //设置密码为16进制的形式到entity对象
            entity.setPassword(simpleHash.toHex());
            entity.setSalt(salt);
        }
    public int updateObject(SysUser entity, String roleIds) {
        //参数验证
        if(entity==null){
            throw new ServiceException("更新对象不能为空");
        }
        if(entity.getId()==null){
            throw new ServiceException("更新用户时id不能为空");
        }
        if(StringUtils.isEmpty(roleIds)){
            throw new ServiceException("用户角色不能为空");
        }
        //更新数据
        
        String password = entity.getPassword();
        if(!StringUtils.isEmpty(password)){
            //将用户输入的密码转换为ByteSource对象
            ByteSource source = ByteSource.Util.bytes(password.getBytes());
            //创建一个随机盐值(采用盐值加密会更加安全)
            String salt=UUID.randomUUID().toString();
            //对密码和盐值进行统一加密,产生一个密文对象
            SimpleHash simpleHash = new SimpleHash("MD5",source,salt);
            //设置密码为16进制的形式到entity对象
            entity.setPassword(simpleHash.toHex());
            entity.setSalt(salt);
        }
        int rows=sysUserDao.updateObject(entity);
        sysUserRoleDao.deleteObject(entity.getId());
        sysUserRoleDao.insertObject(entity.getId(), roleIds.split(","));
        return rows;
    }
    public int saveObject(SysUser entity, String roleIds) {
        entity.setValid(1);
        System.out.println("id="+entity.getId());
        String password=entity.getPassword();
        String username=entity.getUsername();
        if(StringUtils.isEmpty(username)){
            throw new ServiceException("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new ServiceException("密码不能为空");
        }
        //将用户输入的密码转换为ByteSource对象
        ByteSource source = ByteSource.Util.bytes(password.getBytes());
        //创建一个随机盐值(采用盐值加密会更加安全)
        String salt=UUID.randomUUID().toString();
        //对密码和盐值进行统一加密,产生一个密文对象
        SimpleHash simpleHash = new SimpleHash("MD5",source,salt);
        //设置密码为16进制的形式到entity对象
        entity.setPassword(simpleHash.toHex());
        entity.setSalt(salt);
        int rows=sysUserDao.insertObject(entity);
        sysUserRoleDao.insertObject(entity.getId(), roleIds.split(","));
        return rows;
    }
    <update id="updateObject" parameterType="com.school.entity.SysUser">
        update
        <include refid="tableName" />
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="password!=null and password!=''">
                password=#{password},
            </if>
            <if test="salt!=null and salt!=''">
                salt=#{salt},
            </if>
            <if test="mobile!=null and mobile!=''">
                mobile=#{mobile},
            </if>
            <if test="email!=null and email!=''">
                email=#{email},
            </if>
            updated=now()
        </set>
            where id=#{id}
    </update>
    @Override
    public void login(String username, String password) {
        //1.获取shiro中 的subject(主体)对象
        Subject subject=SecurityUtils.getSubject();
        //2.封装用户名和密码到token对象
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        //3.执行登录操作(此方法执行时可能会有异常)
        subject.login(token);
    }
package com.school.service.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
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 org.springframework.stereotype.Service;

import com.school.dao.SysUserDao;
import com.school.entity.SysUser;
/**
 *通过realm这个领域对象对认证领域和授权领域信息进行检测
 */
@Service
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    SysUserDao sysUserDao;

    /**
     * 授权检测
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 认证检测
     * 检测用户身份是否存在,密码是否正确
     * subject.login(token)->
     * SecurityManager->
     * Authentication->
     * ShiroUserRealm->
     * ShiroUserRealm.Authentication
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken=(UsernamePasswordToken)token;
        //获取用户名
        String username = upToken.getUsername();
        //根据用户名查找用户对象
        SysUser user = sysUserDao.findObjectByUserName(username);
        //初始化SimpleAuthenticationInfo对象
        ByteSource saltSource = ByteSource.Util.bytes(user.getSalt().getBytes());
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                user.getUsername(),//用户身份
                user.getPassword(), //已加密 的密码
                saltSource,//盐值对应的byteSource
                getName());//realm的名字
        return info;
    }

}

web.xml

    <!--配置shiro -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>shiroFilter</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

shiro-configs.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd   
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-4.3.xsd
       http://www.springframework.org/schema/data/jpa 
       http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <bean id="userRealm" class="com.school.service.realm.ShiroUserRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5" />
            </bean>
        </property>
    </bean>
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="loginUrl"  value="/login"/>
        <property name="securityManager" ref="securityManager"></property>
        <property name="filterChainDefinitions">
            <value>
                /bootstrap/** =anon
                /build/** =anon
                /dist/** =anon
                /documentation/** =anon
                /font-awesome/** =anon
                /ionicons/** =anon
                /layer/** =anon
                /pages/** =anon
                /plugins/** =anon
                /treegrid/** =anon
                /ztree/** =anon
                /doLogin=anon
                /doLogout=logout
                /**=authc
            </value>
        </property>
    </bean>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"></property>
    </bean>
</beans>
上一篇下一篇

猜你喜欢

热点阅读