zoukankan      html  css  js  c++  java
  • Shiro 十分钟教程

    package com.wjz.demo;
    
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.IncorrectCredentialsException;
    import org.apache.shiro.authc.LockedAccountException;
    import org.apache.shiro.authc.UnknownAccountException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.subject.Subject;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class Quickstart {
    
        private static final Logger log = LoggerFactory.getLogger(Quickstart.class);
    
        public static void main(String[] args) {
            // 获得用户信息
            Subject currentUser = SecurityUtils.getSubject();
            // 获得会话信息
            Session session = currentUser.getSession();
            session.setAttribute("url", "www.baidu.com");
            // 判断用户是否已经登录
            if (currentUser.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken("username", "password");
                token.setRememberMe(true);
                // 当前用户拿着Token去登录系统
                try {
                    currentUser.login(token);
                } catch (UnknownAccountException e) {
                    // TODO 用户不存在
                } catch (IncorrectCredentialsException e) {
                    // TODO 用户名或密码不正确
                    // For example, this exception might be thrown 
                    //if a user's password is "secret" and "secrets" was entered by mistake
                } catch (LockedAccountException e) {
                    // TODO 用户被锁定不能登录
                } catch (AuthenticationException e) {
                    // TODO 认证过程中意想不到的异常
                }
            }
            // Principal -用户的基本信息
            log.info("User ["+ currentUser.getPrincipal() +"] logged in successfully.");
            // 判断会员是否有某个权限 -角色级权限控制
            if (currentUser.hasRole("finance")) {
                // ignore
            }
            // 判断用户是否有权限请求特定的路径 -用户级权限控制
            if (currentUser.isPermitted("finance:selectById")) {
                // ignore
            }
            // 注销登录
            currentUser.logout();
            // TODO 至于谁负责在登录时获得用户数据(用户名和密码、角色和权限),以及谁在运行时真正执行安全检,Shiro 配置使用Realm来完成这些工作
        }
        
    }
  • 相关阅读:
    文档根元素 "beans" 必须匹配 DOCTYPE 根 "null"
    web.xml配置参数context-param和init-param的区别
    web.xml中通过contextConfigLocation的读取spring的配置文件
    Web.xml配置详解之context-param
    xml 文件 和xsd 文件的关系
    事务并发控制
    Java泛型详解
    MongoDB集群
    MongoDB集群——分片
    MongoDB集群——副本集
  • 原文地址:https://www.cnblogs.com/BINGJJFLY/p/8967228.html
Copyright © 2011-2022 走看看