Shiro整合springboot代码

ShiroConfig

package com.springboot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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 {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        /* 添加shiro内置过滤器
         * anon: 无需认证就能访问
         * authc: 授权才能访问
         * user: 有“记住我”功能才能用
         * perms: 拥有某个资源的权限才能访问
         * role: 拥有某个角色权限才能访问
         */
        Map<String, String> map = new LinkedHashMap<>();
        //map.put("/", "anon");
        map.put("/system/admin/**", "perms[1]");
        map.put("/system/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        //设置登录页
        bean.setLoginUrl("/shirologin");
        //未授权页面
        bean.setUnauthorizedUrl("/shirounauthorize");
        return bean;
    }

    //中间商
    //@Qualifier("userRealm")指定类名
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") ShiroRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

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

    //整合shiro thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}

ShiroRealm

package com.springboot.config;

import com.springboot.mapper.AdminMapper;
import com.springboot.pojo.Admin;
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.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    AdminMapper adminMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        Admin admin=(Admin) subject.getPrincipal();
        //设置当前用户权限
        info.addStringPermission(String.valueOf(admin.getRoleId()));
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Admin admin = adminMapper.getByUsername(token.getUsername());
        if (admin == null) {
            return null;//抛出UnknownAccountException
        }
        return new SimpleAuthenticationInfo(admin, admin.getPassword(), "");
//静态账号
//        //用户名,密码
//        String username="admin";
//        String password="111111";
//
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        if(!token.getUsername().equals(username)){
//            return null;//抛出UnknownAccountException
//        }
//
//        //密码认证,shiro做
//        return new SimpleAuthenticationInfo("",password,"");
    }
}

ShiroLoginController 控制器

package com.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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;

@Controller
public class ShiroLoginController {
    @GetMapping("/shirologin")
    public String shiroLogin() {
        return "shiroLogin";
    }

    @RequestMapping("/shirologinpost")
    public String shiroLoginPost(Model model, String username, String password) {
        //拿到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            model.addAttribute("username", username);
            return "system/shiro";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", token.getPrincipal() + "用户名不存在");
            return "shiroLogin";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", token.getPrincipal() + "密码不正确");
            return "shiroLogin";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", token.getPrincipal() + "账户已锁定,请联系管理员");
            return "shiroLogin";
        } catch (AuthenticationException ae) {
            model.addAttribute("msg", ae);
            return "shiroLogin";
        }

//        //all done - log out!
//        subject.logout();
//
//        System.exit(0);
    }
}

前端页面

shiro.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.5">
    <title>shiro首页</title>
</head>
<body>
<div shiro:hasPermission="1">
    权限1
</div>
<div shiro:hasPermission="2">
    权限2
</div>
<div>
    <a th:href="@{/shirologin}">登录</a>
    <a href="/system/shiro">首页</a>
    <a href="/system/admin/list">管理员列表</a>
    <a href="/system/admin/detail">管理员详情</a>
    <a href="/system/user/detail">会员详情</a><br>
    用户名<span th:text="${username}"></span>
    <a th:href="@{/logout}">退出</a>
</div>
</body>
</html>

shiroLogin.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.5">
    <title>shiro登录</title>
</head>
<body>
<form th:action="@{/shirologinpost}" method="post">
    <a href="/system/shiro">首页</a>
    <a href="/system/admin/list">管理员列表</a>
    <a href="/system/admin/detail">管理员详情</a>
    <a href="/system/user/detail">会员详情</a><br>
    用户名:
    <!--用户名默认username-->
    <input type="text" name="username" required autofocus><br>
    密码:
    <!--密码默认password-->
    <input type="password" name="password" required><br>
    <!--记住我默认remember-me-->
    <input type="checkbox" name="remember-me"> 记住我<br>
    <button type="submit">登录</button>
    <div th:text="${msg}"></div>
</form>
</body>
</html>

Maven依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.7.1</version>
</dependency>
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值