Sping boot的Shiro的配置

简介: ; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.mgt.SecurityManager; import org.

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;
    }
}



目录
相关文章
|
25天前
|
安全 Java 数据库
【SpringSecurity】Spring Security 和Shiro对比
【SpringSecurity】Spring Security 和Shiro对比
38 0
|
2天前
|
缓存 安全 Java
Shiro框架以及Spring Boot整合Shiro
Shiro框架以及Spring Boot整合Shiro
Shiro框架以及Spring Boot整合Shiro
|
25天前
|
前端开发 Java 关系型数据库
【Shiro】Springboot集成Shiro
【Shiro】Springboot集成Shiro
52 1
|
4月前
|
XML 缓存 Java
spring shiro配置
spring shiro配置
|
8月前
|
前端开发 关系型数据库 Java
【Shiro】Springboot集成Shiro(一)
【Shiro】Springboot集成Shiro
55 0
|
8月前
|
Java 数据库 数据安全/隐私保护
【Shiro】Springboot集成Shiro(三)
【Shiro】Springboot集成Shiro(三)
70 1
|
8月前
|
Java
【Shiro】Springboot集成Shiro(四)
【Shiro】Springboot集成Shiro(四)
71 0
|
8月前
|
Java
【Shiro】Springboot集成Shiro(二)
【Shiro】Springboot集成Shiro(二)
49 0
|
安全 Java API
springboot整合shiro排雷
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
133 0
springboot整合shiro排雷
|
Java Spring
spring boot 之登录拦截
spring boot 之登录拦截