spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>

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

<div th:if="${session.loginUser!=null}">
    <a th:href="@{/logout}">logout</a>
</div>

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

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

<a th:href="@{/user/edit}">edit</a>
</body>
</html>

/user/add.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
<p th:text="${msg}"></p>
</body>
</html>

/user/edit.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>edit</h1>
<p th:text="${msg}"></p>
</body>
</html>

MyController.java

package com.chen.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.stereotype.Repository;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@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/edit")
    public String edit(){
        return "user/edit";
    }

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

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","error username");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","error password");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "unauthorized can not visit the page!";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

}


UserRealm.java

package com.chen.config;

import com.chen.pojo.User;
import com.chen.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.print("执行了授权");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        //拿到当前登录的对象
        Subject subject= SecurityUtils.getSubject();

        User user=(User)subject.getPrincipal(); //拿到User对象

        //张三能看,李四不能看
        if(user.getName().equals("张三")){
            info.addStringPermission("user:add");
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.print("执行了认证");

//        String name="root";
//        String password="123456";

        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)authenticationToken;

//        if(!usernamePasswordToken.getUsername().equals(name)){
//            return null;//抛出异常
//
//        }
        User user = userService.queryUserByName(usernamePasswordToken.getUsername());

        if(user==null){
            return null;
        }

        Subject currentSubject=SecurityUtils.getSubject();

        Session session=currentSubject.getSession();

        session.setAttribute("loginUser",user);


        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }


}


ShiroConfig.java

package com.chen.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 securityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);

        Map<String,String> filterMap=new LinkedHashMap<>();
        filterMap.put("/user/add","perms[user:add]");
        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();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean(name="userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }


    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}


账户错误如图
spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单_第1张图片
密码错误
spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单_第2张图片
账户密码正确跳到首页

张三用户登录是这样

spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单_第3张图片
李四用户登录是这样的
spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单_第4张图片
李四强行访问不属于他的菜单是这样的
spring boot+shiro+mybatis实现不同用户登录显示不同权限菜单_第5张图片

下载源码

你可能感兴趣的:(后端,mybatis,spring,java)