Shiro整合thymeleaf

实现目标:登录不同的权限,显示不同的内容。

https://blog.csdn.net/qq_44116526/article/details/122032092?spm=1001.2014.3001.5501

1、引入依赖

        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

2、ShiroConfig.java

 //整合ShiroDialet:用来整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }
package com.li.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
//shiroFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//       设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
//        添加shiro的内置过滤器
/*    anon:无需认证就可以访问
      authc:必须认证了才可以访问
      user:拥有了对某个资源的权限才可以访问
      role:拥有某个角色权限才能访问
* */
        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/User/add","authc");
//        filterMap.put("/User/update","authc");

        //授权,正常情况下,没有授权会跳转到未授权页面
        filterMap.put("/User/add", "perms[User:add]");
        filterMap.put("/User/update", "perms[User:update]");
        filterMap.put("/User/*", "authc");
        bean.setFilterChainDefinitionMap(filterMap);
//        设置登录请求
        bean.setLoginUrl("/toLogin");
        //未授权页面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }

    //    DafaultwebSecuityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //    创建realm对象,需要自定义;第一步
//@Bean(name = "userRealm")
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    //整合ShiroDialet:用来整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }
}

3、将用户信息放到Session中,UserRealm.java

 //将用户信息放到Session中
        Subject currentSubject=SecurityUtils.getSubject();
        Session session=currentSubject.getSession();
        session.setAttribute("loginUser",admin);
package com.li.config;

import com.li.Service.adminServiceImpl;
import com.li.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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    adminServiceImpl adminService;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
//       不是 SimpleAuthenticationInfo,是SimpleAuthorizationInfo
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //info.addStringPermission("User:add");
//        拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        admin currentUser=(admin) subject.getPrincipal();//拿到User对象
//        设置当前用户权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》doGetAuthenticationInfo");

//        用户名密码
//        String name="root";
//        String password="123456";
        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
//       连接真实数据库
        admin admin = adminService.queryByname(userToken.getUsername());
//        if (!userToken.getUsername().equals(name))
//        {
//            return null;//抛出异常UnknownAccountException
//        }
        if(admin==null){
            return null;
        }
        //将用户信息放到Session中
        Subject currentSubject=SecurityUtils.getSubject();
        Session session=currentSubject.getSession();
        session.setAttribute("loginUser",admin);
//        密码认证,shiro做
//        return new SimpleAuthenticationInfo("",password,"");
        return new SimpleAuthenticationInfo(admin,admin.getPwd(),"");
        //return new SimpleAuthenticationInfo("",admin.getPwd(),"");
    }
}

4、index.hrml

<!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>
</head>
<body>
首页
<p th:text="${msg}"></p>
<div th:if="session.loginUser==null">
    <p><a th:href="@{/toLogin}">登录</a></p>
</div>
<div shiro:hasPermission="user:add">
    <a th:href="@{/User/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/User/update}">update</a>
</div>


</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shiro整合Thymeleaf是为了在Thymeleaf模板引擎中使用Shiro的功能。首先需要在页面中添加Shiro的命名空间声明,即xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"。然后在项目的pom.xml文件中引入thymeleaf-extras-shiro的依赖,例如:<dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency>。在Shiro的配置类中配置ShiroDialect(Shiro方言)对象,例如:@Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); }。最后,在Thymeleaf的页面中,可以使用Shiro的相关标签和表达式来实现动态检测和授权控制。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【Shiro笔记三】Shiro整合Thymeleaf](https://blog.csdn.net/m0_67393827/article/details/124099555)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Shiro整合thymeleaf](https://blog.csdn.net/qq_44116526/article/details/122115756)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值