SpringBoot_4_integrate_Shiro

hayeka發表於2020-03-08
        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.5.1</version>
        </dependency>
package cn.boxku.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;

/**
 * ————————————————————————————————————————————————
 * CREATED BY since ON 2020/3/7 12:29
 * ————————————————————————————————————————————————
 */
@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager)
    {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //設定安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        /*新增shiro的內建過濾器*/
        /*
        anon
        authc
        user
        perms
        role
        */
        //攔截
        Map<String,String> filterMap = new LinkedHashMap<>();
        //授權
        //filterMap.put("/add","anon");
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/update","perms[user:update]");
        bean.setFilterChainDefinitionMap(filterMap);
        bean.setLoginUrl("/toLogin");
        bean.setUnauthorizedUrl("/unauth");
        return bean;
    }

    //DefaultWebSecurityManger
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm)
    {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //關聯UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //建立realm物件,需要自定義類
    @Bean(name = "userRealm")//預設方法名
    public UserRealm userRealm()
    {
        return new UserRealm();
    }


    //整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect()
    {
        return new ShiroDialect();
    }
}
package cn.boxku.config;

import cn.boxku.pojo.User;
import cn.boxku.service.UserService;
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;

/**
 * ————————————————————————————————————————————————
 * CREATED BY since ON 2020/3/7 12:31
 * ————————————————————————————————————————————————
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=>授權doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        //拿到使用者資訊
        Subject subject = SecurityUtils.getSubject();
        //拿到user物件
        User currentUser = (User) subject.getPrincipal();
        //設定當前使用者許可權
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=>認證doGetAuthorizationInfo");

        /*
        String name = "root";
        String password = "123456";
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        if (!usernamePasswordToken.getUsername().equals(name))
        {
            return null;
        }
        return new SimpleAuthenticationInfo("",password,"");
        */
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //連線真實資料庫
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null)
        {
            return null;
        }
        //密碼認證,shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
package cn.boxku.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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * ————————————————————————————————————————————————
 * CREATED BY since ON 2020/3/7 12:14
 * ————————————————————————————————————————————————
 */
@Controller
public class IndexController {
    @RequestMapping({"/","/index"})
    public String index(Model model)
    {
        model.addAttribute("msg","我是你爹");
        return "index";
    }

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

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

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

    @RequestMapping("/login")
    public String login(String username,String password,Model model)
    {
        //獲取當前使用者
        Subject subject = SecurityUtils.getSubject();
        //封裝登陸資料
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);//執行登入方法,如果沒有異常就ok
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","使用者名稱錯誤");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密碼錯誤");
            return "login";
        }
    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String unauthorized()
    {
        return "未經授權";
    }

}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首頁</h1>
<h1 th:text="${msg}"></h1>
<div shiro:hasPermission="user:add">
    <a th:href="@{/add}">add</a>
</div>

<div shiro:hasPermission="user:update">
    <a th:href="@{/update}">update</a>
</div>
</body>
</html>

mapper注意路徑,路徑寫錯,執行浪費三分鐘,不值得。

mybatis:
  type-aliases-package: cn.boku.pojo
  mapper-locations: classpath:mapper/*.xml
本作品採用《CC 協議》,轉載必須註明作者和本文連結

一個從事軟體開發職業的經濟愛好者