Shiro整合SpringBoot以及Thymeleaf

Shiro整合SpringBoot以及Thymeleaf

1.ShiroConfig

package org.best.config;
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("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();

        // 必须设置 DefaultWebSecurityManager
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //设置登录页面
        //不设置默认为根目录下的/login.jsp
        filterFactoryBean.setLoginUrl("/goLogin");

        //未授权页面

        filterFactoryBean.setUnauthorizedUrl("/403");

        //配置过滤内容
        Map map = new LinkedHashMap<String,String>();
        /**
         * anon:无需认证就可以访问
         * authc:认证才可以访问
         * user:必须设置 记住我 才能用
         * perms:拥有对某个资源的权限才能访问
         * role:拥有某个角色权限才能访问
         */
        //无需认证即可进入页面
        map.put("/","anon");
        map.put("/index","anon");

        //获得权限可访问
        map.put("/user","perms[user]");
        map.put("/admin","perms[admin]");

        //设置过滤链
        filterFactoryBean.setFilterChainDefinitionMap(map);
        return  filterFactoryBean;

    }


    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getMyShiroRealm") MyShiroRealm myShiroRealm){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        //设置realm
        webSecurityManager.setRealm(myShiroRealm);

        return webSecurityManager;
    }



    /**
     * 身份认证realm:认证,权限
     * @return
     */
    @Bean
    public MyShiroRealm getMyShiroRealm(){
        return new MyShiroRealm();
    }
}

2.自定义realm

package org.best.config;

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.best.pojo.User;
import org.best.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //将认证中存进去的principal取出来,转换为user
        User primaryPrincipal = (User) principalCollection.getPrimaryPrincipal();
        //获取对象名
        String username = primaryPrincipal.getUsername();
        //通过用户名获取对象的权限,并进行设置
        info.addStringPermission(userService.findUserByName(username).getRole());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //token是 subject.login(token)传过来的
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //判断用户名是否存在
        User user = userService.findUserByName(userToken.getUsername());
        if (user==null){
            return null;
        }
        /**
         * 校验密码
         * 	第一个参数任意
         * 	第二个参数为密码
         * 	第三个参数为当前参数的名字
         */
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
        //获取shiro的session域对象,并将信息存到狱中
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        return info;
    }
}

3.Controller层

package org.best.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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.best.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    //主页
    @GetMapping(value ={"/index","/"})
    public String index(){
        return "index";
    }

    //去登录页面
    @GetMapping("/goLogin")
    public String goLogin(){
        return "login";
    }

    //user页面
    @GetMapping("/user")
    @ResponseBody
    public String user(){
        return "当前为user界面";
    }

    //admin页面
    @GetMapping("/admin")
    @ResponseBody
    public String admin(){
        return "当前为admin界面";
    }

    //403页面
    @GetMapping("/403")
    public String noType(){
        return "403";
    }



    //登录成功前往主页
    @GetMapping("/login")
    public String login(User user, Model model){

        //如果用户为空,返回登录
        if (user==null){
            return "login";
        }
        //将用户信息放到token中
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        try {
            //调用realm的认证方法
             subject.login(token);
             return "index";
        } catch(IncorrectCredentialsException e){
            //这最好把 所有的 异常类型都背会
            model.addAttribute("message", "密码错误");
            return "login";
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "用户名不存在");
            return "login";
        }


    }

}

4.Service层

package org.best.service;

import org.best.pojo.User;

public interface UserService {
    User findUserByName(String username);
}





package org.best.service.imp;

import org.best.mapper.UserMapper;
import org.best.pojo.User;
import org.best.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUserByName(String username) {
        return userMapper.findUserByName(username);
    }
}

5.持久层

package org.best.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.best.pojo.User;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
    User findUserByName(String username);
}

6.接口映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace为所对应的接口-->
<mapper namespace="org.best.mapper.UserMapper">
    <select id="findUserByName" resultType="user">
      select * from user where username=#{username}
    </select>
</mapper>

7.前端界面

403.html
 
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 403页面
</body>
</html>


index.html

<!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>

<a th:href="@{/goLogin}" th:if="${session.user==null}">登录</a>

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


<div shiro:hasPermission="admin">
    <a th:href="@{/admin}" >admin可点击</a>
</div>


</body>
</html>



login.html


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

<form action="login" method="get">
    <h5 th:text="${message}"></h5>
    用户名:<input type="text" name="username"><br>
    密 码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>

</body>
</html>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页