dubbo和shiro的整合,在服务端做权限验证

dubbo和shiro的整合,在服务端做权限验证

基于dobbo做服务开发后通常会遇上这样一些问题,举个例子:用户的笔记,涉及到CRUD 4个接口,是每一个接口中都要把用户传进去么?
比如:删除接口
定义为 noteService.deleteById(Long noteId)
还是 noteService.deleteById(Long userId, Long noteId)
如果是前者,这个时候如果不验证用户对资源是否有权限直接删除是否合理,尤其是这种可能被用户猜到的ID很容易被恶意调用。如果选第二种的话,那么有很多接口都要这样定义,感觉不够美观,而且也不够严谨。

先说说我的想法:假定所有的服务调用都要通过filter,这个filter能够将sessionId以隐性的方式传参,这样就不用每一个接口去增加userId这个参数,同时由于sessionID是由场门的服务生成的无意义的随机字符,一般类似UUID,当服务端收到这个sessionID后,通过调用session远程服务去获取当前用户的信息,这样服务端就可以知道当前用户是谁,这也避免了消费端的失误造成了用户数据的篡改的可能。

根据设想,将shiro设计成两个模块:ucenter-session-api和ucenter-session-provider,其它的服务端都需要对ucenter-session-api依赖,用于授权web服务对ucenter-session-provider依赖。

 

RemoteSessionService

package com.lenxeon.ucenter.session.api;

import com.lenxeon.ucenter.session.pojo.PermissionContext;
import org.apache.shiro.session.Session;

import java.io.Serializable;


public interface RemoteSessionService {

    /**
     * 获取session
     * @param sessionId
     * @return
     */
    Session getSession(Serializable sessionId);

    /**
     * 创建session
     * @param session
     * @return
     */
    Serializable createSession(Session session);

    /**
     * 更新session
     * @param session
     */
    void updateSession(Session session);

    /**
     * 删除session
     * @param session
     */
    void deleteSession(Session session);

    /**
     * 查询用户的角色和权限信息
     * @param identify
     * @return
     */
    PermissionContext getPermissions(String identify);
}

ShiroCustomFilter,主要是追加x-session-id

package com.lenxeon.ucenter.session.dubbo;

import com.alibaba.dubbo.rpc.*;
import com.lenxeon.ucenter.session.api.RemoteSessionService;
import com.lenxeon.utils.io.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ShiroCustomFilter implements Filter {

    final static Logger logger = LoggerFactory.getLogger(ShiroCustomFilter.class);

    public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
        if(invoker.getInterface().equals(RemoteSessionService.class)){
            //去获取信息
        }else{
            //追加补充信息
            String sessionId = "";
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                //判断是否登陆过
            }
            sessionId = subject.getSession().getId().toString();
            invocation.getAttachments().put("x-session-id", StringUtils.defaultString(sessionId));
        }
        logger.info("CustomFilter.login[{}]", JsonUtils.toJson(invocation.getAttachments()));
        Result result = invoker.invoke(invocation);
        return result;
    }
}

MyResult

package com.lenxeon.ucenter.session.dubbo;

import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;

import java.util.concurrent.Callable;

class MyResult implements Callable {

    private Invoker invoker;

    private Invocation invocation;

    public MyResult(Invoker invoker, Invocation invocation) {
        this.invocation = invocation;
        this.invoker = invoker;
    }

    @Override
    public Result call() throws Exception {
        Result result = invoker.invoke(invocation);
        return result;
    }
}

spring-client-shiro.xml




       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    class="true"/>


    
    class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    class="com.lenxeon.ucenter.session.shiro.client.ClientRealm">
        
        
    

    
    class="org.apache.shiro.web.servlet.SimpleCookie">
        
        
        
        
        
    

    class="org.apache.shiro.web.servlet.SimpleCookie">
        
        
        
        
        
    

    
    class="com.lenxeon.ucenter.session.shiro.client.ClientSessionDAO">
        
        
    

    
    class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        
        
        
        
        
    

    class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    
        
        
    

    
    class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>


    class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        
    

    
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        
        
    

ucenter-session-provider 的结构和涉及的主要代码

RemoteSessionServiceImpl

package com.lenxeon.ucenter.session.api.impl;


import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Sets;
import com.lenxeon.apps.commons.api.IdService;
import com.lenxeon.ucenter.session.api.RemoteSessionService;
import com.lenxeon.ucenter.session.pojo.PermissionContext;
import com.lenxeon.ucenter.user.api.SecurityService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;


@Service
public class RemoteSessionServiceImpl implements RemoteSessionService {

    @Autowired
    private SessionDAO sessionDAO;

    @Reference(version = "1.0.0")
    private IdService idService;

    @Reference(version = "1.0.0")
    private SecurityService securityService;

    private static final Logger logger = LoggerFactory.getLogger(RemoteSessionServiceImpl.class);


    @Override
    public Session getSession(Serializable sessionId) {
        return sessionDAO.readSession(sessionId);
    }

    @Override
    public Serializable createSession(Session session) {
        return sessionDAO.create(session);
    }

    @Override
    public void updateSession(Session session) {
        sessionDAO.update(session);
    }

    @Override
    public void deleteSession(Session session) {
        sessionDAO.delete(session);
    }

    @Override
    public PermissionContext getPermissions(String identify) {
        PermissionContext permissionContext = new PermissionContext();
        permissionContext.setRoles(Sets.newHashSet("po", "sm", "team"));
        permissionContext.setPermissions(Sets.newHashSet("system:delete_department", "system:user:create", "system:user:delete"));
        return permissionContext;
    }
}

spring-local-shiro.xml




       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://code.alibabatech.com/schema/dubbo
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    class="true"/>

    
    class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    class="com.lenxeon.ucenter.session.shiro.local.LimitRetryHashedMatcher">
        
        
        
        
    

    
    
    

    
    class="com.lenxeon.ucenter.session.shiro.local.RedisSessionDAO">
        
        
    

    
    
          
        
        
    

    
    class="com.lenxeon.ucenter.session.shiro.local.UserSessionFactory"/>

    
    class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    
        
        
        
        
        
        
        
    

    interface="com.lenxeon.ucenter.user.api.UserService" version="1.0.0"/>

    
    class="com.lenxeon.ucenter.session.shiro.local.UserRealm">
        
        
    

    class="com.lenxeon.ucenter.session.shiro.local.RedisCacheManager"/>

    
    class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        
            
                
            
        
        
        
    

    
    class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    
    
    
    

    
    
    
    
    
    
    
    

    
    
    

    class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        
    

    
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        
        
    


在其它服务端中使用时

需要依赖:ucenter-session-api
需要配置:shiroCustomFilter
需要引用: spring-client-shiro.xml

 

web服务中关于shiro的配置

<import resource="classpath*:META-INF/spring/spring-local-shiro.xml"/>

    class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        
    

    
    
    
    class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
            
                *.js = anon
                *.css=anon
                /modules/**=anon
                /static/**=anon
                /weixin/**=anon
                /users/forget.html=anon
                /users/reset.html=anon
                /users/login.html=anon
                /users/**=anon
                /oauth2/**==anon
                /test/**==anon
                

                /api/v1/users/random=anon
                /api/v1/users/sign_in=anon
                /api/v1/users/login=anon
                /api/v1/users/session=anon
                /api/v1/users/mobile/check=anon
                /api/v1/users/password/forgot=anon
                /api/v1/users/password/reset=anon
                /api/v1/users/email/check=anon
                /api/v1/security/captcha/**=anon
                /api/ids**=anon
                /api/ids/**=anon
                /**=authc

                
                
                
                
                
                
            
        
    

 

posted on 2017-08-09 11:10  yufan27209 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/yufan27209/p/7324190.html

你可能感兴趣的:(dubbo和shiro的整合,在服务端做权限验证)