Spring Boot整合 Shiro安全框架

**

Spring Boot 整合Shiro 安全框架

**

关于Spring Boot整合Shiro安全框架的步骤,以后项目中用到 可以按照 步骤配置应用起来

1.pom文件添加依赖

1.pom文件添加依赖

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>

2.新建一个包 config 创建两个配置类

package com.hengyang.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 getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //设置shiro的内置过滤器
        /**
         * anno:无需认证所有人都可以访问
         * authc: 必须认证了才能访问
         * user: 必须拥有记住我才能访问
         * perms: 拥有某个资源的权限才能访问
         * role: 拥有某个角色权限才能访问
         */

//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权
        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;
    }



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

    //创建 realm 对象 ,需要自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


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

}

package com.hengyang.config;

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

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        //添加权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//拿到user对象
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){//没有该用户
            return null;
        }

        //当前登录用户放进session
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //密码认证
        return new SimpleAuthenticationInfo(user,user.getUser_password(),"");
    }
}

3.UserController 用户登录

package com.hengyang.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }


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

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

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


    /**
     * 用户信息 账号和密码封装成token
     *  UsernamePasswordToken token = new UsernamePasswordToken(username, paddword);
     * 用户的信息封装成一个令牌 然后直接  subject.login(token);
     * 用try catch接住
     * UnknownAccountException = 账号不存在
     * IncorrectCredentialsException = 密码错误
     * @param username
     * @param paddword
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(String username,String paddword,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //使用用户的登录信息创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, paddword);
        try {
            subject.login(token);//执行登录方法,如果没有异常就说明OK
            return "index";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }

    /**
     * 本地登出页面
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value="/logout",method= RequestMethod.GET)
    public String logout(RedirectAttributes redirectAttributes ){
        //使用权限管理工具进行用户的退出,跳出登录,给出提示信息
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "/login";
    }



}


4.Shiro 整合 thymeleaf 前端不显示 没有权限的功能按钮

1.引入 pom 依赖

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

2.前端代码 首页 加上个 xmlns:shiro=“http://www.thymeleaf.org/thymeleaf-extras-shiro”

3.在UserRealm配置类的认证方法里往session里存放当前登录用户 ,供前端 判断是不是有该用户

        //当前登录用户放进session
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

4.前端进行判断


<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>

<p th:text="${msg}"></p>

<hr>
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">添加</a>
</div>

<div shiro:hasPermission="user:update">
    | <a th:href="@{/user/update}">修改</a>
</div>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值