SpringBoot整合Shiro

1. 创建SpringBoot项目

此处因为是笔记,为了更容易复习我把Servic和Mapper个移除了,此处三层只有Controller
项目源码可自取:源码

2.添加依赖

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.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot_shiro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_shiro</name>
    <description>SpringBoot整合Shiro</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--SpringBoot整合shiro的依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.5.2</version>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--添加nekohtml依赖的原因是我不想使用严格的HTML5标准(每个标签都是一对的),加入这个依赖后就可以使用不严格的了-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
    </dependencies>

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

</project>

3.创建几个简单的HTML页面

在这里插入图片描述
index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Welcome</h1>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body>
<p th:text="${{tips}}"></p>
<form th:action="@{/login}">
    账号<input name="username"><br>
    密码<input type="password" name="userpwd"><br>
    <input type="submit" value="登陆">
</form>
</body>
</html>

add.html和update.html只是一个随便写了一个<p></p>标签的html页面

4.Controller层

indexController.java

package com.example.springboot_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class indexController {

    @RequestMapping({"/","index.html"})
    public String toIndex(Model model){
        model.addAttribute("tips","Hello Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String UserAdd(){
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String Userupdate(){
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String Login(){
        return "login";
    }


    @RequestMapping("/login")
    public String login(String username,String userpwd,Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd);
        try {
            System.out.println("切到UserRealm");
            subject.login(token);//执行登陆
            System.out.println("从UserRealm切换回来");
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("tips","用户名异常");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("tips","密码错误");
            return "login";
        }

    }

}

5.Shiro的三大对象注入到Spring中

Shiro有三大对象,按顺序分别是:Subject,SecurityManager和Realms
但实际上编写的顺序是要倒着来的,因为SecurityManager需要Realms,而Subject需要SecurityManager

UserRealm.java

package com.example.springboot_shiro.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

public class UserRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("UserReal进行授权");
        return null;
    }

    //认证,点击登陆就会执行该方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("UserReal进行认证");
        //假数据
        String username = "zs";
        String userpwd = "123";
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //用户名认证
        if(!token.getUsername().equals(username)){
            return null;//返回null会自动抛出 UnknownAccountException异常
        }
        //密码认证直接交给Shiro即可
        return new SimpleAuthenticationInfo("",userpwd,"");
    }
}

ShiroConfig .java

package com.example.springboot_shiro.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //创建realm对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //创建DefaultWebSecurityManager也就是securityManager,并将其与UserRealm关联起来
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager ){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(securityManager);
        //设置shiro的内置过滤器
        /*
            anon:无需认证就可以访问
            authc:无需认证就可以访问
            usser:必须用有记住我功能该可以访问
            perms:拥有某个资源的权限才可以启动,注意:这里说的是资源而不是角色
            role:拥有某个角色权限开可以访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add","anon");
        filterMap.put("/user/update","authc");
        //通配符写法,拦截所有请求 filterMap.put("/**","authc");

        bean.setFilterChainDefinitionMap(filterMap);
        //设置登陆请求
        bean.setLoginUrl("/toLogin");
        // 登录成功请求
        bean.setSuccessUrl("/index");
        return bean;
    }
}

成功

项目结构如下在这里插入图片描述
application.yml里面写了点东西是为了关闭缓存和使用不严格的w3c标准

spring:
  thymeleaf:
    cache: false
    mode: LEGACYHTML5 #为了使用不严格的w3c标准,不然很麻烦
    encoding: utf-8
    servlet:
      content-type: text/html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值