记录Shiro学习

2020-01-02  本文已影响0人  ccccaixiaohao

1.shiro的简介

shiro的介绍参照:https://blog.csdn.net/wanliangsoft/article/details/86533754
技术博客:https://www.jianshu.com/p/5ee3acc40dfe

2.shiro的验证部分

1.自定义Realm的验证部分

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByName(userName);
        if(null == user) {
            return null;
        }
        else {
            SimpleAuthenticationInfo authenticationInfo =
                    new SimpleAuthenticationInfo(user.getName(),user.getPassword(),ByteSource.Util.bytes(user.getName()),getName());        
            return authenticationInfo;
        }
        
    }

从数据库查出密码交给SimpleAuthenticationInfo进行比较认证

2.业务层处理shiro比较的结果

public String login(User user) {
        String result = "";
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
            subject.login(token);
            result = "success";
        }
        catch (DisabledAccountException e) {
            result = "用户已被禁用";
        }
        catch(UnknownAccountException e) {
            result = "用户不存在";
        }
        catch(IncorrectCredentialsException e) {
            result = "用户账号密码错误";
        }
        catch (AuthenticationException e) { 
            result = "登入失败";
        }
        return result;
    }

认证后,若shiro没有抛出异常就代表登录成功,抛出不同的异常代表不同的认证失败原因。

3.注册用户时MD5加密部分

public int regist(User user) {
        int result = 0;
        //加盐加密,盐用用户名
        String saltPassword = new Md5Hash(user.getPassword(), user.getName(), 10).toString();
        user.setPassword(saltPassword);
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        result = userMapper.insertSelective(user);
        return result;
    }

new Md5Hash(明文密码,盐值,加密次数)

4.在shiro配置类中给md5配置对应参数

//配置加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5"); // 散列算法
        hashedCredentialsMatcher.setHashIterations(10); // 散列次数
        return hashedCredentialsMatcher;
    }

3.shiro的授权部分

1.在自定义realm将用户的角色和权限给到shiro

//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = principalCollection.toString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //权限赋值
        String permissions = userService.getPermissionByUserName(name);
        String[] permissionArr = permissions.split(",");
        for(int i=0;i<permissionArr.length;i++) {
            authorizationInfo.addStringPermission(permissionArr[i]);
        }
        //角色赋值
        String roleName = userService.getRoleNameByUserName(name);
        authorizationInfo.addRole(roleName);
        return authorizationInfo;
    }

2.如果页面有对应shiro标签或者后台有对应检查权限的代码shiro就会进行相应的校验

<div>
        <label>操作</label>
        <shiro:hasPermission name="role:view">
            <button id="roleView">角色查看</button>
        </shiro:hasPermission>      
        <shiro:hasPermission name="role:add">
            <button>角色添加</button>
        </shiro:hasPermission>
        <shiro:hasPermission name="role:update">
            <button>角色修改</button>
        </shiro:hasPermission>
        <shiro:hasPermission name="role:delete">
            <button>角色删除</button>
        </shiro:hasPermission>
    </div>

3.对应的配置文件

1.myRealm

package com.cwh.shiro;

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.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 org.springframework.beans.factory.annotation.Autowired;

import com.cwh.entity.User;
import com.cwh.service.UserService;

public class MyShiroRealm extends AuthorizingRealm {
    
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = principalCollection.toString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //权限赋值
        String permissions = userService.getPermissionByUserName(name);
        String[] permissionArr = permissions.split(",");
        for(int i=0;i<permissionArr.length;i++) {
            authorizationInfo.addStringPermission(permissionArr[i]);
        }
        //角色赋值
        String roleName = userService.getRoleNameByUserName(name);
        authorizationInfo.addRole(roleName);
        return authorizationInfo;
    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByName(userName);
        if(null == user) {
            return null;
        }
        else {
            SimpleAuthenticationInfo authenticationInfo =
                    new SimpleAuthenticationInfo(user.getName(),user.getPassword(),ByteSource.Util.bytes(user.getName()),getName());        
            return authenticationInfo;
        }
        
    }

}

2.shiro配置类

package com.cwh.shiro;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

/**
 * shiro的配置类
 *
 */
@Configuration
public class ShiroConfig {
    
     @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
    
    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }
    
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, String> filterChainDefinitionMap = new HashMap<String, String>();
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthc");
        shiroFilterFactoryBean.setSuccessUrl("/index");
//        
        filterChainDefinitionMap.put("/login", "anon");
//        filterChainDefinitionMap.put("/user/login/**", "anon");
//        filterChainDefinitionMap.put("/index/**", "perms[index:list]");
        filterChainDefinitionMap.put("/*", "authc");
//        filterChainDefinitionMap.put("/role/roleView", "perms[role:view]");   

//        filterChainDefinitionMap.put("/authc/renewable", "perms[Create,Update]");
//        filterChainDefinitionMap.put("/authc/removable", "perms[Delete]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
    
    //配置加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5"); // 散列算法
        hashedCredentialsMatcher.setHashIterations(10); // 散列次数
        return hashedCredentialsMatcher;
    }
    
    //配置数据源realm
    @Bean(name = "authRealm")
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myRealm = new MyShiroRealm();
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myRealm;
    }
    
    //配置securityManager
    @Bean(name = "securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myShiroRealm());
        return manager;
    }               

}

测试工程有存百度云盘

上一篇 下一篇

猜你喜欢

热点阅读