Shiro 的整合 Spring 之自定义Realm

本文介绍如何使用Apache Shiro框架进行用户注册及密码加密,并实现自定义Realm以完成认证和授权过程。通过示例代码展示了如何在保存用户时进行密码加密处理,以及如何创建并配置自定义Realm。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇文章我们介绍了Shiro自带的JdbcRealm的使用,传送门:第一个例子JdbcRealm的使用

在做登录实现之前我们先做注册实现,很简单只需要做常规的insert即可,需要注意就密码需要加密。

    public int save(UserEntity entity) {
        entity.setPassword(CryptUtils.sha512(entity.getLoginName(),entity.getPassword()));
        //添加角色
        return super.save(entity);
    }
/**
 * 密码工具类
 */
public class CryptUtils {

    public static String generateSalt(String text){
        return new SimpleHash("md5",text,text,1024).toHex().substring(0,16);
    }

    public static String sha512(String username,String passwrod){
        return new SimpleHash("sha-512",passwrod,generateSalt(username),1024).toBase64();
    }

}

自定义Realm的用法和JdbcRealm的用法差不多,下面我们来写一个

新建一个类名为:SystemAuthorizingRealm,继承自:AuthorizingRealm

public class SystemAuthorizingRealm extends AuthorizingRealm {


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        return null;
    }

}

当然也可以继承AuthenticatingRealm,只需实现认证方法doGetAuthenticationInfo(),AuthorizingRealm是AuthenticatingRealm的子类,实现了认证和授权功能,比父类更强大。

doGetAuthenticationInfo(AuthenticationToken authenticationToken):认证方法,用来登录的时候跟数据库用户名密码匹配的一个方法,只需要返回一个SimpleAuthenticationInfo,下面我们来实现一下。

public class SystemAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        UserEntity user = userService.getByUsername(username);
        if (user != null){
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword()
                    ,ByteSource.Util.bytes(CryptUtils.generateSalt(user.getLoginName())),getName());
            return simpleAuthenticationInfo;
        }else {
            return null;
        }
    }

}

new SimpleAuthenticationInfo():构造有需要传递2-4参数都有,可自行选择,我这里用的是4个参数分别的用户名、密码、密码盐,realm名称。密码盐我是根据用户名来实现,你们自己实现即可。


    public SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) {
        this.principals = new SimplePrincipalCollection(principal, realmName);
        this.credentials = credentials;
    }

    public SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) {
        this.principals = new SimplePrincipalCollection(principal, realmName);
        this.credentials = hashedCredentials;
        this.credentialsSalt = credentialsSalt;
    }

    public SimpleAuthenticationInfo(PrincipalCollection principals, Object credentials) {
        this.principals = new SimplePrincipalCollection(principals);
        this.credentials = credentials;
    }

    public SimpleAuthenticationInfo(PrincipalCollection principals, Object hashedCredentials, ByteSource credentialsSalt) {
        this.principals = new SimplePrincipalCollection(principals);
        this.credentials = hashedCredentials;
        this.credentialsSalt = credentialsSalt;
    }

doGetAuthorizationInfo(PrincipalCollection principalCollection):授权方法,用于登录成功后执行的授权方法,具体实现如下:

public class SystemAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private RoleService roleService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        UserEntity user = userService.getByUsername(username);
        if (user != null){
            List<RoleEntity> roleList = user.getRoleList();
            //添加角色权限
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (RoleEntity roleEntity : roleList) {
                RoleEntity role = roleService.getByRoleName(roleEntity.getEnname());
                info.setStringPermissions(role.getMenuList().stream().map(MenuEntity::getPermission).collect(Collectors.toSet()));
            }
            info.setRoles(roleList.stream().map(RoleEntity::getEnname).collect(Collectors.toSet()));
            return info;
        }
        return null;
    }

}

最后返回一个SimpleAuthorizationInfo(),设置从数据库查到的角色权限即可。

Spring配置realm

    <bean class="com.demo.sys.security.realm.SystemAuthorizingRealm" id="systemAuthorizingRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
                <property name="hashIterations" value="1024"></property>
                <property name="hashAlgorithmName" value="sha-512"></property>
                <property name="storedCredentialsHexEncoded" value="false"></property>
            </bean>
        </property>
    </bean>


    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <property name="realm" ref="systemAuthorizingRealm"></property>
    </bean>

后述问题

1. 不想在Web页面URL后面显示;JSSONID=xxx,如:http:localhost:8080/login;JSESSONID=xxx

    <bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager" id="sessionManager">
        <property name="sessionIdUrlRewritingEnabled" value="false"></property>
    </bean>

    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <property name="realm" ref="systemAuthorizingRealm"></property>
        <property name="sessionManager" ref="sessionManager"></property>
    </bean>

2. 控制台报:JSESSONID SessionException: There is no session with id [9f3e2cbd-5a1a-4813-8138-a41497a9

    <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg name="name" value="shiro.sesssion"/>
        <property name="path" value="/"/>
    </bean>

    <bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager" id="sessionManager">
        <property name="sessionIdCookie" ref="simpleCookie"></property>
        <property name="sessionIdUrlRewritingEnabled" value="false"></property>
    </bean>

    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <property name="realm" ref="systemAuthorizingRealm"></property>
        <property name="sessionManager" ref="sessionManager"></property>
    </bean>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值