Springboot整合shiro前后分离

强颜欢笑 提交于 2019-12-26 16:01:18

全局异常监控 AppExceptionAdivse

@RestControllerAdvice //以json串的形式返回出去
public class AppExceptionAdivse {
   @ExceptionHandler(value= {UnauthorizedException.class})
   public Map<String, Object> unauthorized() {
       Map<String, Object> map=new HashMap<>();
       map.put("code", 302);
       map.put("msg", "未授权");
       System.out.println("未授权");
       return map;
   }

}

LoginController


@RestController
@RequestMapping("login")
public class LoginController {



   /**
    * 登陆
    */
   @RequestMapping("login")
   public Map<String,Object> login(String username,String password,HttpSession session) {
      Map<String,Object> map=new HashMap<>();
      //封装token
      UsernamePasswordToken   token=new UsernamePasswordToken(username, password);
      //得到主体
      Subject subject = SecurityUtils.getSubject();
      try {
         subject.login(token);
         ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
         session.setAttribute("user", activerUser.getUser());
         map.put("code", 200);
         map.put("msg", "登陆成功");
         return map;
      } catch (AuthenticationException e) {
         e.printStackTrace();
         map.put("code", -1);
         map.put("msg", "登陆失败 用户名或密码不正确");
         return map;
      }
   }
   
   
   
}

UserController


@RestController
@RequestMapping("user")
public class UserController {


   @RequiresPermissions(value= {"user:query"})
   @RequestMapping("query")
   public Map<String,Object> query() {
      Map<String,Object> map=new HashMap<>();
      map.put("msg", "query");
      return map;
   }
   @RequiresPermissions(value= {"user:add"})
   @RequestMapping("add")
   public Map<String,Object> add() {
      Map<String,Object> map=new HashMap<>();
      map.put("msg", "add");
      return map;
   }
   @RequiresPermissions(value= {"user:update"})
   @RequestMapping("update")
   public Map<String,Object> update() {
      Map<String,Object> map=new HashMap<>();
      map.put("msg", "update");
      return map;
   }
   @RequiresPermissions(value= {"user:delete"})
   @RequestMapping("delete")
   public Map<String,Object> delete() {
      Map<String,Object> map=new HashMap<>();
      map.put("msg", "delete");
      return map;
   }
   @RequiresPermissions(value= {"user:export"})
   @RequestMapping("export")
   public Map<String,Object> export() {
      Map<String,Object> map=new HashMap<>();
      map.put("msg", "export");
      return map;
   }
}

ShiroLoginFilter

public class ShiroLoginFilter  extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //if (isAjax(request)) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code", -1);
        resultData.put("msg", "未登录!");
        httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
   /* } else {
         // saveRequestAndRedirectToLogin(request, response);
         *//**
         * @Mark 非ajax请求重定向为登录页面
         *//*
         httpServletResponse.sendRedirect("/login.jsp");
      }*/
        return false;
    }

    private boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sxt</groupId>
    <artifactId>springboot_shiro1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_shiro1</name>
    <description>集成shiro的传统方式</description>

    <properties>
        <java.version>1.8</java.version>
        <shiro.version>1.4.2</shiro.version>
        <fastjson.version>1.2.60</fastjson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <!-- thymeleaf依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--shrio和thymeleaf集成的扩展依赖,为了能在页面上使用xsln:shrio的标签 -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.13</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ShiroAutoConfiguration


/**
 * @program: 0812springboot
 * @author: 雷哥
 * @create: 2019-12-18 15:58
 **/
@Configuration
@EnableConfigurationProperties(ShiroProperties.class)
public class ShiroAutoConfiguration {

    @Autowired
    private ShiroProperties shiroProperties;

    /**
     * 创建凭证匹配器
     */
    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName(shiroProperties.getHashAlgorithmName());
        credentialsMatcher.setHashIterations(shiroProperties.getHashIterations());
        return  credentialsMatcher;
    }

    /**
     * 创建realm
     */
    @Bean
    public UserRealm userRealm(CredentialsMatcher credentialsMatcher){
        UserRealm userRealm=new UserRealm();
        //注入凭证匹配器
        userRealm.setCredentialsMatcher(credentialsMatcher);
        return userRealm;
    }

    /**
     * 声明安全管理器
     */
    @Bean("securityManager")
    public SecurityManager securityManager(UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return  securityManager;
    }


    /**
     * 配置过滤器 Shiro 的Web过滤器 id必须和web.xml里面的shiroFilter的 targetBeanName的值一样
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        //注入安全管理器
        bean.setSecurityManager(securityManager);
        //注入登陆页面
        bean.setLoginUrl(shiroProperties.getLoginUrl());
        //注入未授权的页面地址
        bean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl());
        //注入过滤器
        Map<String, String> filterChainDefinition=new HashMap<>();

        //注入放行地址
        if(shiroProperties.getAnonUrls()!=null&&shiroProperties.getAnonUrls().length>0){
            String[] anonUrls = shiroProperties.getAnonUrls();
            for (String anonUrl : anonUrls) {
                filterChainDefinition.put(anonUrl,"anon");
            }
        }
        //注入登出的地址
        if(shiroProperties.getLogoutUrl()!=null){
            filterChainDefinition.put(shiroProperties.getLogoutUrl(),"logout");
        }
        //注拦截的地址
        String[] authcUrls = shiroProperties.getAuthcUrls();
        if(authcUrls!=null&&authcUrls.length>0){
            for (String authcUrl : authcUrls) {
                filterChainDefinition.put(authcUrl,"authc");
            }
        }
        bean.setFilterChainDefinitionMap(filterChainDefinition);
        //创建自定义filter
        ShiroLoginFilter filter=new ShiroLoginFilter();
        Map<String,Filter> map=new HashMap<>();
        map.put("authc",filter);
        bean.setFilters(map);

        return bean;
    }


    /**
     * 注册过滤器
     */
    @Bean
    public FilterRegistrationBean<DelegatingFilterProxy> filterRegistrationBeanDelegatingFilterProxy(){
        FilterRegistrationBean<DelegatingFilterProxy> bean=new FilterRegistrationBean<>();
        //创建过滤器
        DelegatingFilterProxy proxy=new DelegatingFilterProxy();
        bean.setFilter(proxy);
        bean.addInitParameter("targetFilterLifecycle","true");
        bean.addInitParameter("targetBeanName","shiroFilter");
//        bean.addUrlPatterns();
        List<String> servletNames=new ArrayList<>();
        servletNames.add(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
        bean.setServletNames(servletNames);
        return bean;
    }


    /**
     * 这里是为了能在html页面引用shiro标签,上面两个函数必须添加,不然会报错
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    /*加入注解的使用,不加入这个注解不生效--开始*/
    /**
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }
    /*加入注解的使用,不加入这个注解不生效--结束*/
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!