XXXRealm

package com.cetc30.auth.server.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.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;

/**
 * @author meihongliang
 * @since 2021/10/15 15:50 周五
 */
public class MhlRealm extends AuthorizingRealm {


    public MhlRealm() {
        // md5验证匹配器
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        // 循环加密次数
        md5.setHashIterations(3);
        // 设置验证对象
        this.setCredentialsMatcher(md5);
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String inputUsername = principals.getPrimaryPrincipal().toString();
        // 构造一个授权凭证
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 添加 用户角色
        authorizationInfo.addRole("superManager");
        authorizationInfo.addRoles(Arrays.asList("admin", "manager"));
        // 添加用户权限
        authorizationInfo.addStringPermission("permission");
        authorizationInfo.addStringPermissions(Arrays.asList("permission1", "permission2"));
        return authorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        String passwordFromMysql = "password";
        String yourSalt = "salt";

        // username 登陆用户
        // passwordFromMysql 数据库查出来的密码
        // yourSalt 加盐加密的盐值
        // realmName 当前Realm的名字
        return new SimpleAuthenticationInfo(username, passwordFromMysql, ByteSource.Util.bytes(yourSalt), "MhlRealm");
    }

    public static void main(String[] args) {
        String password = "123456";
        String csdnName = "casblanca";
        Md5Hash md5Hash = new Md5Hash(password, csdnName, 3);
        //打印结果:e36e406088fcbe05c70ec1ab33bffa64
        System.out.println(md5Hash);
    }

    //@Test
    //public void generatePassword() {
    //    String password = "123456";
    //    String csdnName = "小大宇";
    //    Md5Hash md5Hash = new Md5Hash(password, csdnName, 3);
    //    //打印结果:e36e406088fcbe05c70ec1ab33bffa64
    //    System.out.println(md5Hash);
    //}
}

上一篇:02-shiro中的核心架构


下一篇:2、Web项目,Spring整合Shiro