springboot集成shiro的一个小demo

工具:idea+maven

maven

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>

shiro

Realm
/**
 * @author : white.hou
 * @description : 关联管理员用户的Realm
 * @date: 2018/11/10_19:49
 */
public class RootRealm extends AuthorizingRealm {
    @Autowired
    private RootService rootService;

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Logger loggerAuthenticationInfo  =LoggerFactory.getLogger(getClass());
        loggerAuthenticationInfo.info("执行认证逻辑");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        /**
         * 判断接收到的信息
         */
        loggerAuthenticationInfo.debug("获取到的账号: " + usernamePasswordToken.getUsername() + "," + "获取到的密码: " + Arrays.toString(usernamePasswordToken.getPassword()));
        Root root=rootService.findRootTokenByRootName(usernamePasswordToken.getUsername());
        if (root == null) {
            /**
             * Shiro底层返回 UnknownAccountException
             */
            return null;
        }
        /**
         * 判断密码
         */
        return new SimpleAuthenticationInfo(root, root.getPassword(), "");
    }

    /**
     * 资源授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Logger loggerAuthorizationInfo =LoggerFactory.getLogger(getClass());
        loggerAuthorizationInfo.info("执行授权逻辑");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Subject subject=SecurityUtils.getSubject();
        Root root=(Root)subject.getPrincipal();
        Root dbRoot=rootService.findRootTokenByRootName(root.getRootName());
        simpleAuthorizationInfo.addStringPermission(dbRoot.getIdentity());
        loggerAuthorizationInfo.debug("获取到的数据库对象的名字是: "+root.getRootName()+"获取到的数据库对象的身份标识是: "+root.getIdentity());
        return simpleAuthorizationInfo;
    }
}
config
/**
 * @author : white.hou
 * @description : shiro配置类
 * @date: 2018/11/10_19:49
 */
@Configuration
public class ShiroConfig {
    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        /**
         * 关联securityManager
         */
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        /**
         * 添加Shiro内置过滤器
         * 常用:
         *    anon:无需认证(登录)就能访问
         *    authc:必须认证才能访问
         *    user:使用rememberMe功能可以直接访问
         *    perms:该资源必须得到资源权限才能访问
         *    role:该资源必须得到角色权限才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/", "authc");
        filterMap.put("/commons/*","authc");
       // filterMap.put("/*/**","authc");
        /**
         * 添加授权逻辑 ,未获得授权调转到指定页面
         */
        filterMap.put("/user/*", "perms[user:root]");
        filterMap.put("/root/*","perms[admin:root]");

        /**
         * 跳转到指定页面,参数为@RequsetMapping
         */
        shiroFilterFactoryBean.setLoginUrl("/tologin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     * @param rootRealm
     * @return
     */
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("rootRealm") RootRealm rootRealm){
        DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
        /**
         * 关联Realm
         */
        defaultWebSecurityManager.setRealm(rootRealm);
        return defaultWebSecurityManager;
    }
    /**
     * 创建RootRealm
     * @return
     */
    @Bean(name = "rootRealm")
    public RootRealm getRootRealm(){
    return new RootRealm();
   }
}

contorller层
/**
 * @author : white.hou
 * @description : 登录的controller 类
 * @date: 2018/11/10_21:06
 */
@Controller
public class LoginController {
    /**
     * 登录逻辑处理模块
     */
    @PostMapping("/login")
    public String login(@RequestParam("rootName") String rootName, @RequestParam("password") String password, Model model) {
        /**
         * Shiro便携认证操作:
         *   1 获取subject
         *   2 封装用户数据
         *   3 执行登录方法
         */
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(rootName, password);
        try {
            subject.login(usernamePasswordToken);
       /*      //界面优化的坑
            model.addAttribute("rootIdentity",usernamePasswordToken.getUsername());*/
            // 重定向
            return "redirect:/main.html";
        } catch (UnknownAccountException e) {
            /**
             * 登录失败:用户名不存在
             */
            model.addAttribute("msg", "用户名不存在,请校验后登录");
            return "/login";
        } catch (IncorrectCredentialsException e) {
            /**
             * 登录失败:密码错误
             */
            model.addAttribute("msg", "密码错误,请重新输入");
            return "/login";
        }
    }
    /**
     * 跳转控制模块
     */
    @RequestMapping("/tologin")
    public String tologin() {
        return "/login";
    }
    /**
     * 未授权页面
     *
     * @return
     */
    @RequestMapping("/noAuth")
    public String noAuth() {
        return "/noAuth";
    }
}
页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="登录">
    <meta name="author" content="white.hou">
    <title></title>
    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.css}" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="main.html" th:action="login" method="post">
    <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt=""
         width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
    <strong type="hidden" class="alert alert-warning" th:text="${msg}" th:if="${msg!=null}" >Warning!</strong>
    <label class="sr-only" th:text="#{login.username}">Username</label>
    <input type="text" name="rootName" class="form-control" placeholder="Username" th:placeholder="#{login.username}"
           required="" autofocus="">
    <label class="sr-only" th:text="#{login.password}">Password</label>
    <input type="password" name="password" class="form-control" placeholder="Password"
           th:placeholder="#{login.password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"/> [[#{login.remember}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
    <p class="mt-5 mb-3 text-muted">© 2018-2019</p>
    <a class="btn btn-sm" th:href="@{login.html(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{login.html(l='en_US')}">English</a>
</form>
</body>

</html>

项目地址

springboot 集成 shiro的一个小demo](https://github.com/Hz12306/manage.git)

over~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值