Spingboot的Shiro的配置

is考拉發表於2018-11-30

Config


import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Configuration
public class ShiroConfig {


    /***
     * 具體的驗證規則實現類
     */
    @Resource
    ShiroRealm shiroRealm;

    @Bean
    public EhCacheManager ehCacheManager() {
        return null;
    }

    @Bean
    public LoginFilterShiro loginFilterShiro() {
        return new LoginFilterShiro();
    }

    @Bean
    public FilterRegistrationBean delegatingFilterProxy() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetFilterLifecycle(true);
        proxy.setTargetBeanName("shiroFilter");
        filterRegistrationBean.setFilter(proxy);
        return filterRegistrationBean;
    }

    /***
     * 許可權管理
     * @return
     */
    @Bean
    public SecurityManager securityManager() {
        log.info("----------------載入shiro許可權管理器---------------");
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(shiroRealm);
        return defaultWebSecurityManager;
    }

    /***
     * Shiro過濾器,用於過濾相關請求
     * @param securityManager
     * @return
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        log.info("----------------載入shiro許可權過濾器---------------");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setLoginUrl("/account/unauth");

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("authc", new LoginFormAuthenticationFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        Map<String, String> pathMap = new HashMap<>();
        pathMap.put("/js/**", "anon");
        pathMap.put("/images/**", "anon");
        pathMap.put("/plugins/**", "anon");
        pathMap.put("/webjars/**", "anon");
        pathMap.put("/account/login", "anon");
        pathMap.put("/swagger-ui.html", "anon");
        pathMap.put("/swagger-resources/**", "anon");
        pathMap.put("/v2/**", "anon");
        //
        pathMap.put("/appsvr/**", "anon");
        pathMap.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(pathMap);

        return shiroFilterFactoryBean;
    }

    /***
     * Shiro 用於生效註解
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        log.info("----------------載入SourceAdvisor---------------");
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


}

Realm


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    @Autowired
    private BusUserService busUserService;

    @Autowired
    private BusUserRoleService busUserRoleService;

    @Autowired
    private BaseRoleService baseRoleService;

    @Value("${shiroRealm.BIAuthentic}")
    private Boolean authentic;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) super.getAvailablePrincipal(principalCollection);
        log.info("登入驗證,使用者資訊----{}", userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("authc");
        Subject subject=SecurityUtils.getSubject();
        List<String> roleList = (List<String>) subject.getSession().getAttribute("roleCodeList");
        simpleAuthorizationInfo.addRoles(roleList);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("------------------Shiro身份認證-----------------");
        BILoginToken token = (BILoginToken) authenticationToken;
        if (null == token) {
            throw new AuthenticationException();
        }
        String userName = token.getUsername();
        String password = String.valueOf(token.getPassword());
        String validCode = token.getValidCode();
        String requestId = token.getRequestId();
        log.info("token中的userName:" + userName + " validCode:" + validCode + " requestId:" + requestId);

       

            //查詢使用者角色關係表
            BusUserRole busUserRole = new BusUserRole();
            busUserRole.setUserId(busUser.getId());
            EntityWrapper<BusUserRole> busUserRoleEntityWrapper = new EntityWrapper<>(busUserRole);
            List<BusUserRole> busUserRoleList = busUserRoleService.selectList(busUserRoleEntityWrapper);
            List<String>roleCodeList=new ArrayList<>();
            List<String> roleIdList = new ArrayList<>();
            if (0 < busUserRoleList.size()) {
                for (BusUserRole temp : busUserRoleList) {
                    roleIdList.add(temp.getRoleId());
                }
            }
            log.info("使用者的角色Id為:" + JsonUtil.objectToJson(roleIdList));

            //查詢角色列表
            List<BaseRole> baseRoleList = baseRoleService.getRoleByRoleIds(roleIdList);
            log.info("查詢到的角色列表為:" + JsonUtil.objectToJson(baseRoleList));
            List<Integer> roleList = new ArrayList<>();
            for (BaseRole temp : baseRoleList) {
                String roleCode = temp.getId();
                if (RoleEnum.ROLE_CODE_OPERATION.getDesc().equals(roleCode)) {
                    roleList.add(1);
                }
                if (RoleEnum.ROLE_CODE_SALE.getDesc().equals(roleCode)) {
                    roleList.add(2);
                }
                if (RoleEnum.ROLE_CODE_ADMIN.getDesc().equals(roleCode)) {
                    roleList.add(0);
                }
                roleCodeList.add(temp.getRoleCode());
            }

            //token返回賦值
            token.setBaseRoleList(roleList);
            token.setUsername(busUser.getUsername());
            token.setUm(busUser.getUm());
            token.setId(busUser.getId());
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, ByteSource.Util.bytes(userName), getName());
            Subject subject = SecurityUtils.getSubject();
            subject.getSession().setAttribute("userInfo", busUser);
            subject.getSession().setAttribute("roleList", baseRoleList);
            subject.getSession().setAttribute("roleCodeList",roleCodeList);
            return simpleAuthenticationInfo;
    }
}


相關文章