Spring Boot 整合 Shiro ,两种方式全总结!

在 Spring Boot 中作权限管理,通常来讲,主流的方案是 Spring Security ,可是,仅仅从技术角度来讲,也可使用 Shiro。java

今天松哥就来和你们聊聊 Spring Boot 整合 Shiro 的话题!git

通常来讲,Spring Security 和 Shiro 的比较以下:github

  1. Spring Security 是一个重量级的安全管理框架;Shiro 则是一个轻量级的安全管理框架
  2. Spring Security 概念复杂,配置繁琐;Shiro 概念简单、配置简单
  3. Spring Security 功能强大;Shiro 功能简单
  4. ...

虽然 Shiro 功能简单,可是也能知足大部分的业务场景。因此在传统的 SSM 项目中,通常来讲,能够整合 Shiro。web

在 Spring Boot 中,因为 Spring Boot 官方提供了大量的很是方便的开箱即用的 Starter ,固然也提供了 Spring Security 的 Starter ,使得在 Spring Boot 中使用 Spring Security 变得更加容易,甚至只须要添加一个依赖就能够保护全部的接口,因此,若是是 Spring Boot 项目,通常选择 Spring Security 。spring

这只是一个建议的组合,单纯从技术上来讲,不管怎么组合,都是没有问题的。apache

在 Spring Boot 中整合 Shiro ,有两种不一样的方案:后端

  1. 第一种就是原封不动的,将 SSM 整合 Shiro 的配置用 Java 重写一遍。
  2. 第二种就是使用 Shiro 官方提供的一个 Starter 来配置,可是,这个 Starter 并无简化多少配置。

原生的整合

  • 建立项目

建立一个 Spring Boot 项目,只须要添加 Web 依赖便可:安全

项目建立成功后,加入 Shiro 相关的依赖,完整的 pom.xml 文件中的依赖以下:cookie

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>
  • 建立 Realm

接下来咱们来自定义核心组件 Realm:session

public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        if (!"javaboy".equals(username)) {
            throw new UnknownAccountException("帐户不存在!");
        }
        return new SimpleAuthenticationInfo(username, "123", getName());
    }
}

在 Realm 中实现简单的认证操做便可,不作受权,受权的具体写法和 SSM 中的 Shiro 同样,不赘述。这里的认证表示用户名必须是 javaboy ,用户密码必须是 123 ,知足这样的条件,就能登陆成功!

  • 配置 Shiro

接下来进行 Shiro 的配置:

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }
    
    @Bean
    SecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }
    
    @Bean
    ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        bean.setLoginUrl("/login");
        bean.setSuccessUrl("/index");
        bean.setUnauthorizedUrl("/unauthorizedurl");
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/doLogin", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}

在这里进行 Shiro 的配置主要配置 3 个 Bean :

  1. 首先须要提供一个 Realm 的实例。
  2. 须要配置一个 SecurityManager,在 SecurityManager 中配置 Realm。
  3. 配置一个 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路径拦截规则等。
  4. 配置登陆和测试接口。

其中,ShiroFilterFactoryBean 的配置稍微多一些,配置含义以下:

  • setSecurityManager 表示指定 SecurityManager。
  • setLoginUrl 表示指定登陆页面。
  • setSuccessUrl 表示指定登陆成功页面。
  • 接下来的 Map 中配置了路径拦截规则,注意,要有序。

这些东西都配置完成后,接下来配置登陆 Controller:

@RestController
public class LoginController {
    @PostMapping("/doLogin")
    public void doLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            System.out.println("登陆成功!");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登陆失败!");
        }
    }
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
    @GetMapping("/login")
    public String  login() {
        return "please login!";
    }
}

测试时,首先访问 /hello 接口,因为未登陆,因此会自动跳转到 /login 接口:

而后调用 /doLogin 接口完成登陆:

再次访问 /hello 接口,就能够成功访问了:

使用 Shiro Starter

上面这种配置方式实际上至关于把 SSM 中的 XML 配置拿到 Spring Boot 中用 Java 代码从新写了一遍,除了这种方式以外,咱们也能够直接使用 Shiro 官方提供的 Starter 。

  • 建立工程,和上面的同样

建立成功后,添加 shiro-spring-boot-web-starter ,这个依赖能够代替以前的 shiro-webshiro-spring 两个依赖,pom.xml 文件以下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring-boot-web-starter</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>
  • 建立 Realm

这里的 Realm 和前面的同样,我就再也不赘述。

  • 配置 Shiro 基本信息

接下来在 application.properties 中配置 Shiro 的基本信息:

shiro.sessionManager.sessionIdCookieEnabled=true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
shiro.unauthorizedUrl=/unauthorizedurl
shiro.web.enabled=true
shiro.successUrl=/index
shiro.loginUrl=/login

配置解释:

  1. 第一行表示是否容许将sessionId 放到 cookie 中
  2. 第二行表示是否容许将 sessionId 放到 Url 地址拦中
  3. 第三行表示访问未获受权的页面时,默认的跳转路径
  4. 第四行表示开启 shiro
  5. 第五行表示登陆成功的跳转页面
  6. 第六行表示登陆页面
  • 配置 ShiroConfig
@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }
    @Bean
    DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }
    @Bean
    ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/doLogin", "anon");
        definition.addPathDefinition("/**", "authc");
        return definition;
    }
}

这里的配置和前面的比较像,可是再也不须要 ShiroFilterFactoryBean 实例了,替代它的是 ShiroFilterChainDefinition ,在这里定义 Shiro 的路径匹配规则便可。

这里定义完以后,接下来的登陆接口定义以及测试方法都和前面的一致,我就再也不赘述了。你们能够参考上文。

总结

本文主要向你们介绍了 Spring Boot 整合 Shiro 的两种方式,一种是传统方式的 Java 版,另外一种则是使用 Shiro 官方提供的 Starter,两种方式,不知道你们有没有学会呢?

本文案例,我已经上传到 GitHub ,欢迎你们 star:https://github.com/lenve/javaboy-code-samples

关于本文,有问题欢迎留言讨论。

关注公众号牧码小子,专一于 Spring Boot+微服务以及先后端分离等全栈技术,按期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!

相关文章
相关标签/搜索