我是靠谱客的博主 直率大船,最近开发中收集的这篇文章主要介绍shiro安全框架shiro中的第一个程序用户认证shiro中认证流程源码shiro自定义RealmMD5+Salt实现java练习shiro (不涉及数据库) demospringboot集成shiro,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

shiro学习

shiro中的第一个程序用户认证

 //1.创建安全管理器对象
        DefaultSecurityManager securityManager=new DefaultSecurityManager();

        //2.给安全管理器设置realm
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));

        //3.SecurityUtils 给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //4.关键对象subject主体
        Subject subject=SecurityUtils.getSubject();

        //5.创建令牌
        UsernamePasswordToken   token=new UsernamePasswordToken("xiaoou","1123");
        try {
            subject.login(token);
            System.out.println("认证状态:"+subject.isAuthenticated());
        }catch (UnknownAccountException w){
            System.out.println("账号不存在!");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误!");
        }finally {
            System.out.println("认证结束 ");
        }

shiro中认证流程源码

认证:1.最终执行用户名比较 是在SimpleAccountRealm类中的doGetAuthenticationInfo 方法中完成用户名校验的

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        SimpleAccount account = getUser(upToken.getUsername());

        if (account != null) {

            if (account.isLocked()) {
                throw new LockedAccountException("Account [" + account + "] is locked.");
            }
            if (account.isCredentialsExpired()) {
                String msg = "The credentials for account [" + account + "] are expired";
                throw new ExpiredCredentialsException(msg);
            }

        }

        return account;
    }

2.最终密码校验是在AuthenticatingRealm类中的assertCredentialsMatch方法中完成密码校验的

protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
    CredentialsMatcher cm = getCredentialsMatcher();
    if (cm != null) {
        if (!cm.doCredentialsMatch(token, info)) {
            //not successful - throw an exception to indicate this:
            String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
            throw new IncorrectCredentialsException(msg);
        }
    } else {
        throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
                "credentials during authentication.  If you do not wish for credentials to be examined, you " +
                "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
    }
}

总结:

AuthenticatingRealm   认证realm          doGetAuthenticationInfo
AuthorizingRealm         授权realm         doGetAuthorizationInfo

shiro自定义Realm

测试类:

        //创建SecuirityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //设置自定义realm
        defaultSecurityManager.setRealm(new CustomerRealm());
        //将安全工具类设置安全工具类
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //通过安全管理器获取Subject(主体)
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("x","6");
        try {
            subject.login(usernamePasswordToken);
            System.out.println("状态"+subject.isAuthenticated());

        }catch (UnknownAccountException e){
            System.out.println("账号错误");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }

自定义的realm

package org.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.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class CustomerRealm extends AuthorizingRealm {


    //授权realm
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //因为暂时还没有涉及到授权 所有授权可以忽略
        return null;
    }

    //认证realm
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //在token中获取用户名
        Object principal = token.getPrincipal();
       //模拟使用mybatis查询数据库
        if (principal.toString().equals("x")){
            //参数一 返回数据库中正确的用户名  参数二返回数据库中的正确密码   参数三 提供当前realm的名字
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal.toString(),"6",this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}

MD5+Salt实现

自定realm

package org.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.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class Md5realm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取身份信息
        Object principal = token.getPrincipal();

        //根据用户名查询数据库
        if (principal.toString().equals("xiaoou")){
            //参数一返回数据库中正确的用户名  参数二返回数据库中的正确密码  参数三注册时使用的随机盐  参数四提供当前realm的名字
            return new SimpleAuthenticationInfo(principal.toString(),"66bd74861c4a331b7c6e55df3101fa63", ByteSource.Util.bytes("6*asdas55**-"),this.getName());
        }

        return null;
    }
}

测试类

package org.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.realm.CustomerRealm;
import org.realm.Md5realm;

public class TestShiro3 {
    public static void main(String[] args) {
        //创建安全管理器
        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();

        //自定义realm
        Md5realm md5realm = new Md5realm();



        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);

        //设置realm使用hash凭证匹配器
        md5realm.setCredentialsMatcher(credentialsMatcher);

        //注入自定义realm
        defaultSecurityManager.setRealm(md5realm);

        //将安全管理器注入到安全工具
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("xiaoou","633633");

        try {
            subject.login(token);
            System.out.println("登录成功!");
        }catch (UnknownAccountException e){
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }




    }
}

java练习shiro (不涉及数据库) demo

自定义realm

package org.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.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;

public class Md5realm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object primaryPrincipal = principals.getPrimaryPrincipal();  //拿到用户
        System.out.println(primaryPrincipal.toString());
        SimpleAuthorizationInfo d=new SimpleAuthorizationInfo();
        d.addRole("admin");
        d.addRole("user");
        d.addStringPermission("user:*:01 ");
        return d;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取身份信息
        Object principal = token.getPrincipal();

        //根据用户名查询数据库
        if (principal.toString().equals("xiaoou")){
            //参数一返回数据库中正确的用户名  参数二返回数据库中的正确密码  参数三注册时使用的随机盐  参数四提供当前realm的名字
            return new SimpleAuthenticationInfo(principal.toString(),"66bd74861c4a331b7c6e55df3101fa63", ByteSource.Util.bytes("6*asdas55**-"),this.getName());
        }

        return null;
    }
}

main测试

package org.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.realm.CustomerRealm;
import org.realm.Md5realm;

import java.util.Arrays;

public class TestShiro3 {
    public static void main(String[] args) {
        //创建安全管理器
        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();

        //自定义realm
        Md5realm md5realm = new Md5realm();


        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);

        //设置realm使用hash凭证匹配器
        md5realm.setCredentialsMatcher(credentialsMatcher);

        //注入自定义realm
        defaultSecurityManager.setRealm(md5realm);

        //将安全管理器注入到安全工具
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("xiaoou","633633");

        try {
            subject.login(token);
            System.out.println("登录成功!");
        }catch (UnknownAccountException e){
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }

        if (subject.isAuthenticated()){  //认证成功进行授权

            //基于单角色权限控制
            System.out.println("***"+subject.hasRole("admin"));

            //基于多角色权限控制
            System.out.println(subject.hasAllRoles(Arrays.asList("admin","user")));

            //是否具有其中一个角色
            System.out.println(subject.hasRoles(Arrays.asList("admin"))[0]);

            //基于权限字符串的访问控制 资源访问标识符:操作:资源类型
            System.out.println("访问控制:"+subject.isPermitted("user:*:01"));

            System.out.println("访问控制:"+subject.isPermitted("user:update:02"));

            //分别具有哪些权限
            boolean[] permitted = subject.isPermitted("user:*:01", "admin:*:10");

            for (boolean b:permitted
                 ) {
                System.out.println("id权限"+b);
            }

            //同时具有哪些权限
            boolean permittedAll = subject.isPermittedAll("user:*:01", "admin:update:02");
            System.out.println(permittedAll);


        }




    }
}

springboot集成shiro

Shiro依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.5.3</version>
</dependency>

ShiroConfig (配置类)

package com.shiro.bootshiro;

import com.shiro.shiro.CutomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * 用来整合shiro相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1.创建shiroFilter      负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShirodFilterFactortBean(DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        Map<String,String> map=new HashMap<String,String>();
        //配置系统公共资源
        map.put("/user/login","anon");
        map.put("/zhu.html","anon");
        map.put("/user/zhu","anon");
        //配置系统受限资源
        map.put("/**","authc");  //authc 请求这个资源需要认证和授权

        shiroFilterFactoryBean.setLoginUrl("/login.html");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    //2.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }
    //3.创建自定义的realm
    @Bean
    public Realm getRealm(){
        CutomerRealm cutomerRealm=new CutomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数
        hashedCredentialsMatcher.setHashIterations(1024);
        cutomerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return cutomerRealm;
    }
}

MvcExecption(异常处理类)

package com.shiro.controller;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@ControllerAdvice
public class MvcExecption {

    @ExceptionHandler({AuthorizationException.class})   //负责处理AuthorizationException异常。
    public String handlerExceptio() {
        System.out.println("你没有权限删除用户!");
        return "redirect:/index.html";
    }

}

Shirocontroller(控制器类)

package com.shiro.controller;

import com.shiro.pojo.Shiro;
import com.shiro.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;



@Controller
@RequestMapping("/user")
public class Shirocontroller {

    @Autowired
    private ShiroService shiroService;

    @RequestMapping("/login")   //登录
    public String login(String name,String password){
            //获取主体对象
        Subject subject= SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(name,password));
            return "redirect:/index.html";  //登录成功去主页
        }catch (UnknownAccountException e){
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误!");
        }
        return "redirect:/login.html";  //登录页
    }

    @RequestMapping("/exit")   //退出登录
    public String login1(){
    Subject subject=SecurityUtils.getSubject();
    subject.logout();  //登出
        return "redirect:/login.html";
    }

    @RequestMapping("/zhu")  //注册用户
    public String login2(Shiro shiro){   //逻辑处理层在service
   int i= shiroService.save(shiro);
   if (i>0){
       System.out.println("注册成功");
       return "redirect:/login.html";    //成功与否都去登录页面
   }
        System.out.println("注册失败");
        return "redirect:/login.html";
    }
    //注解方式的鉴别身份
/*@RequiresRoles("admin1")                                  //判断角色是否是admin*/
@RequiresRoles(value = {"admin","user"})                    //判断主角色是否同时具有两个角色
/*@RequiresPermissions(value = {"admin:*:01","admin:*:02"})  判断著角色是否同时具有当前权限*/
/*@RequiresPermissions("user:update:01")                    判断当前角色是否具有当前权限*/
    @RequestMapping("/jia")
    public String deleteuser(){           //根据权限执行本方法
    System.out.println("删除一位普通用户!");
/*
        //代码方式的鉴别身份
        Subject admin=SecurityUtils.getSubject();
        if (admin.hasRole("admin1")){
            //执行业务逻辑
            System.out.println("删除了一位普通用户!");
        }else{
            System.out.println("无权删除");

        }
*/
        return "redirect:/index.html";
    }

}

ShiroMapper(Dao层)

package com.shiro.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shiro.pojo.Pers;
import com.shiro.pojo.Shiro;

import java.util.List;

public interface ShiroMapper extends BaseMapper<Shiro> {
    int save(Shiro shiro);

    Shiro selectshiro(String name);

    List<Pers> selectshiro1(Integer tid);
}

ShiroMapper(Dao接口映射文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiro.dao.ShiroMapper">


    <resultMap id="sedome" type="Shiro" >
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
<collection property="roles" javaType="list" ofType="Role" >
    <id property="id" column="id1"></id>
    <result property="name" column="name" ></result>
</collection>
    </resultMap>

    <select id="selectshiro" parameterType="String" resultMap="sedome" >
SELECT so.id,so.username,re.id AS id1,re.name FROM shiro so
INNER JOIN usrole us ON so.id=us.uid
INNER JOIN role re ON re.id=us.rid WHERE so.username=#{nmae}
    </select>


    <select id="selectshiro1" parameterType="int" resultType="Pers" >
SELECT ps.id,ps.name  FROM pers ps
INNER JOIN ropers rs ON rs.persid=ps.id
INNER JOIN role re ON re.id=rs.roleid WHERE re.id=#{tid}
    </select>

</mapper>

Pers(权限实体类)

package com.shiro.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@AllArgsConstructor
@Accessors(chain =true)
@NoArgsConstructor
/**
 * 权限
 */
public class Pers {
    private Integer id;
    private String name;
}

Role(角色实体类)

package com.shiro.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@AllArgsConstructor
@Accessors(chain =true)
@NoArgsConstructor
/**
 * 角色
 */
public class Role {
    private int id;
    private String name;
}

Shiro(用户实体类)

package com.shiro.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;

@Data
@Accessors(chain =true)
@AllArgsConstructor
@NoArgsConstructor
/**
 * 用户
 */
public class Shiro {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String username;
    private String userpassword;
    private String salt;
    @TableField(exist = false)
    private List<Role> roles;

}

Saltutils(随机盐生成工具类)

package com.shiro.saltutils;

import java.util.Random;

/**
 * /随机盐工具类
 */
public class Saltutils {
    public static String getSalt(int n){  //根据传入的用户密码长度随机生成盐
        //定义随机盐
        char [] chars="qwertyuiopasdfghjklzxcvbnm,963852741/*-+123457890--=".toCharArray();
        StringBuffer stringBuffer=new StringBuffer();
        for (int i=0;i<n;i++){
            char aChar = chars[new Random().nextInt(chars.length - 1)];
            stringBuffer.append(aChar);
        }
        return stringBuffer.toString();
    }

}

ShiroService(逻辑层)

package com.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shiro.pojo.Pers;
import com.shiro.pojo.Shiro;

import java.util.List;

public interface ShiroService {
    int save(Shiro shiro);

    Shiro selectshiro(QueryWrapper<Shiro> queryWrapper);

    List<Pers> selectshiro1(Integer tid);

    Shiro list(String name);
}

ShiroServiceImpl(逻辑层实现类)

package com.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shiro.dao.ShiroMapper;
import com.shiro.pojo.Pers;
import com.shiro.pojo.Shiro;
import com.shiro.saltutils.Saltutils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private ShiroMapper shirodao;

    @Override
    public int save(Shiro shiro) {  //处理注册逻辑
        String salt= Saltutils.getSalt(shiro.getUserpassword().length());  //拿到随机生成的salt
        shiro.setSalt(salt);
        Md5Hash md5Hash = new Md5Hash(shiro.getUserpassword(),salt,1024); //设置md5+sqlt+hash
        shiro.setUserpassword(md5Hash.toHex());
        return shirodao.insert(shiro);
    }

    @Override
    public Shiro selectshiro(QueryWrapper<Shiro> queryWrapper) {
        return shirodao.selectOne(queryWrapper);
    }

    @Override
    public Shiro list(String name) {
        return shirodao.selectshiro(name);
    }

    @Override
    public List<Pers> selectshiro1(Integer tid) {
        return shirodao.selectshiro1(tid);
    }
}

CutomerRealm(自定义realm)

package com.shiro.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shiro.pojo.Pers;
import com.shiro.pojo.Shiro;
import com.shiro.service.ShiroService;
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.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class CutomerRealm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

           String name=(String) principals.getPrimaryPrincipal();  //获取用户身份信息

        Shiro usernamelist = shiroService.list(name);  //根据用户信息(名字)查询用户角色
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();

               if (!CollectionUtils.isEmpty(usernamelist.getRoles())){   //查询到该用户角色新消息

            usernamelist.getRoles().forEach(r->{  //循环角色信息

                simpleAuthorizationInfo.addRole(r.getName());  //赋予角色

                List<Pers> persList=shiroService.selectshiro1(r.getId());  //拿到当前的角色具有的全部权限

                if (!CollectionUtils.isEmpty(persList)){   //判断不为空

                    persList.forEach(t->{  //循环权限信息

                        simpleAuthorizationInfo.addStringPermission(t.getName());  //赋予权限

                    });
                }

            });
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String prin=(String) token.getPrincipal();  //获取用户名

        Shiro shiro=shiroService.selectshiro(new QueryWrapper<Shiro>().eq("username",prin)); //拿到当前用户信息

       if (!ObjectUtils.isEmpty(shiro)){   //判断不为空
           // 用户名+密码(MD5+盐+hash散列)+自定义盐值+当前域名
           return new SimpleAuthenticationInfo(shiro.getUsername(),shiro.getUserpassword(), ByteSource.Util.bytes(shiro.getSalt()),this.getName());
       }
        return null;
    }



}

最后

以上就是直率大船为你收集整理的shiro安全框架shiro中的第一个程序用户认证shiro中认证流程源码shiro自定义RealmMD5+Salt实现java练习shiro (不涉及数据库) demospringboot集成shiro的全部内容,希望文章能够帮你解决shiro安全框架shiro中的第一个程序用户认证shiro中认证流程源码shiro自定义RealmMD5+Salt实现java练习shiro (不涉及数据库) demospringboot集成shiro所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部