美文网首页
记录Shiro学习

记录Shiro学习

作者: ccccaixiaohao | 来源:发表于2020-01-02 15:16 被阅读0次

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;
    }               

}

测试工程有存百度云盘

相关文章

  • SpringBoot+shiro+mybatis实现权限登录

    SpringBoot+shiro+mybatis+Thymeleaf实现权限登录系统 记录一下,学习shiro的一...

  • 我的Shiro学习(一)

    前言 本文主要是记录自己学习Shiro框架的过程以及内容心得等,防止自己忘记。 什么是Shiro? Shiro是一...

  • 记录Shiro学习

    1.shiro的简介 shiro的介绍参照:https://blog.csdn.net/wanliangsoft/...

  • shiro学习全记录

    1.shiro整体架构 1.Authenticator=>认证器:负责用户登录登出2.Authoorizer=>授...

  • (五)整合SSM

    只记录有关shiro的部分,详见:http://how2j.cn/k/shiro/shiro-ssm/1727.h...

  • SpringBoot + Shiro 整合

    --本文记录了 SpringBoot + Shiro整合,包括 Shiro 登录认证(多个 Realm认证),Se...

  • Shiro安全框架学习记录

    参考来源 Shiro安全框架 一、Shiro认识和介绍 1、什么是ShiroApache的强大灵活的开源安全框架认...

  • Shiro官网学习记录

    ​ 官网文档很适合入门,搬运一波入门教程 ​ Shiro框架学习 ​ shiro.ini ​ Quic...

  • 学习shiro笔记

    工作需要,学习shiro。阅读张开涛的Shiro教程 AuthenticationInfo作用

  • 权限框架Shiro学习之表结构设计

    权限框架Shiro学习之表结构设计 Shiro是一款优秀的开源安全框架,学习Shiro大家可以参考张开涛老师的博客...

网友评论

      本文标题:记录Shiro学习

      本文链接:https://www.haomeiwen.com/subject/elhooctx.html