SpringBoot学习- 8、整合Shiro

Shiro是什么,引自百度百科:Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

关于Shiro网上讲的很多,以下代码是来自网上几篇博客文章的代码集成,

下面是集成步骤

1、pom.xml添加以下内容

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.3.2</version>
</dependency>

2、config包添加以下类,标蓝色行如果不写会有默认页面。

package com.jgui.config;

import com.jgui.shiro.CustomFormAuthenticationFilter;
import com.jgui.shiro.CustomRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Autowired
    CustomRealm customRealm;
    @Autowired
    CustomFormAuthenticationFilter customAuthenticationFilter;
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/front/**", "anon");
        filterChainDefinitionMap.put("/api/**", "anon");
        //filterChainDefinitionMap.put("/hello", "anon");

        filterChainDefinitionMap.put("/admin/**", "authc");
        filterChainDefinitionMap.put("/user/**", "authc");
        //主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截 剩余的都需要认证
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;

    }

    @Bean
    public CustomFormAuthenticationFilter customAuthenticationFilter(){
        return new CustomFormAuthenticationFilter();
    }
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setRealm(new CustomRealm());
        return defaultSecurityManager;
    }

    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        return customRealm;
    }
}

3、当访问未授权的界面就会跳到/login 控制器对应的页面,如果我们使用前后端分离,那么就需要返回一个json,以下是一种实现方法

添加一个filter

package com.jgui.shiro;

import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;

@Slf4j
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        return false;
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (!isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                            "Authentication url [" + getLoginUrl() + "]");
                }

                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.setStatus(HttpStatus.CONFLICT.value());
                JSONObject json = new JSONObject();
                json.put("message","没有权限访问");
                Writer writer = httpServletResponse.getWriter();
                writer.write(json.toJSONString());
                writer.flush();
                writer.close();
            }else {
                return executeLogin(request, response);
            }
        }
        return false;
    }

}

4、然后在ShiroConfig内添加如下代码

 // 自定义过滤器
        Map<String, Filter> filterMap = shiroFilterFactoryBean.getFilters();

        filterMap.put("restful_return", customAuthenticationFilter);

        shiroFilterFactoryBean.setFilters(filterMap);

位置如下图

5、这个时候返回的就是一个json了。

6、以上内容参考博客

https://blog.csdn.net/weixin_33709219/article/details/91433272

https://blog.csdn.net/catoop/article/details/69210140

https://blog.csdn.net/cckevincyh/article/details/79629022

https://blog.csdn.net/nthack5730/article/details/51019516

上一篇:

SpringBoot学习- 7、问题Could not autowire. No beans of ‘xxxx‘ type found处理

原文地址:https://www.cnblogs.com/zhaogaojian/p/12203602.html

时间: 2024-08-04 08:43:24

SpringBoot学习- 8、整合Shiro的相关文章

SpringBoot 优雅的整合 Shiro

Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最大的Web和企业应用程序.网上找到大部分文章都是以前SpringMVC下的整合方式,很多人都不知道shiro提供了官方的starter可以方便地跟SpringBoot整合. 请看shiro官网关于springboot整合shiro的链接:Integrating Apache Shiro into S

SpringBoot学习:整合Mybatis,使用HikariCP超高性能数据源

一.添加pom依赖jar包: 1 <!--整合mybatis--> 2 <dependency> 3 <groupId>org.mybatis.spring.boot</groupId> 4 <artifactId>mybatis-spring-boot-starter</artifactId> 5 <version>1.1.1</version> 6 </dependency> 7 8 <!

SpringBoot学习--04SpringBoot整合Mybatis(上)(配置mybatis generator,PageHelper)

陆陆续续又忙了几天,继续写. 本篇仿照着优秀的文章的书写,加上自己的理解和踩过的坑,原文地址:https://www.jianshu.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin 环境/版本一览: 开发工具:eclipse springboot: 2.0.1.RELEASE jdk:1.8.0_40 maven:3.3.9 额外功能:

shiro框架学习-2-springboot整合shiro及Shiro认证授权流程

1. 添加依赖 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>mysql</groupId> 7 <artifactId>mys

SpringBoot整合Shiro (二)

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码学和会话管理.相比较Spring Security,shiro有小巧.简单.易上手等的优点.所以很多框架都在使用shiro. Shiro包含了三个核心组件:Subject, SecurityManager 和 Realms. Subject 代表了当前用户的安全操作. SecurityManager 则管理所有用户的安全操作.它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityMana

springboot学习笔记-5 springboot整合shiro

http://www.cnblogs.com/hlhdidi/p/6376457.html 亲自验证,该帖真实有效 shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/  它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和shiro整合的功能!接下来就用springboot结合springmvc,mybatis,整合shiro完成对于用户登录的判定和权限的验证. 1.准备数据库表结构 这里主要涉及到五张表:

SpringBoot系列十二:SpringBoot整合 Shiro

1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初的 SpringSecurity(这个开发框架非常不好用,但是千万不要 以为 SpringSecurity 没有用处,它在 SpringCloud 阶段将发挥重大的作用).但是现在如果要想整合 Shiro 开发框架有一点很遗憾, SpringBoot 没有直接的配置支持,它不像整合所谓的 Kafka.Redis.DataSource,也就是说如果要想整合 Shiro 开

SpringBoot整合Shiro 涉及跨域和@Cacheable缓存/@Transactional事务注解失效问题(五)

1. 跨域(多出现在前后端分离项目中) (1) 跨域介绍可参考:跨域(CORS) (2) SpringBoot中解决跨域方式有: A. 使用@CrossOrigin注解: B. 实现Filter类,重写doFilter方法 package com.ruhuanxingyun.config; import cn.hutool.core.util.StrUtil; import org.springframework.context.annotation.Configuration; import

SpringBoot整合Shiro 集成Redis缓存(六)

简介:由于考虑到项目后期分布式部署,所以缓存由ehcache改为redis,而redis既有单机版部署,也有分布式部署,所以二者需要兼容. 1. maven依赖 <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>3.1.0</version> </dependency> 2. 设