1.目录结构

2.log4j.properties

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries
log4j.logger.org.apache=WARN # Spring
log4j.logger.org.springframework=WARN # Default Shiro logging
log4j.logger.org.apache.shiro=TRACE # Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

3.shiro.ini

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# ============================================================================= # -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = , president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz # -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'delete' (action) the user (type) with
# license plate 'zhangsan' (instance specific id)
goodguy = user:delete:zhangsan

4.Quickstart.java

package com.hxlz.helloworld;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // 获取当前的 Subject. 调用 SecurityUtils.getSubject();
Subject currentUser = SecurityUtils.getSubject(); // 测试使用 Session
// 获取 Session: Subject#getSession()
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("---> Retrieved the correct value! [" + value + "]");
} // 测试当前的用户是否已经被认证. 即是否已经登录.
// 调动 Subject 的 isAuthenticated()
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装为 UsernamePasswordToken 对象
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
// rememberme
token.setRememberMe(true);
try {
// 执行登录.
currentUser.login(token);
log.info("----> 该用户已登录!");
}
// 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.
catch (UnknownAccountException uae) {
log.info("----> There is no user with username of " + token.getPrincipal());
return;
}
// 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。
catch (IncorrectCredentialsException ice) {
log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
return;
}
// 用户被锁定的异常 LockedAccountException
catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// 所有认证时异常的父类.
catch (AuthenticationException ae) {
}
}
//通过currentUser.getPrincipal()获取登录用户名
log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully."); // 测试是否有某一个角色. 调用 Subject 的 hasRole 方法.
if (currentUser.hasRole("schwartz")) {
log.info("----> May the Schwartz be with you!");
} else {
log.info("----> Hello, mere mortal.");
return;
} //test a typed permission (not instance-level)
// 测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。
if (currentUser.isPermitted("lightsaber:weild")) {
log.info("----> You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
} //a (very powerful) Instance Level permission:
// 测试用户是否具备某一个行为.
if (currentUser.isPermitted("user:delete:zhangsan")) {
log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
} // 执行登出. 调用 Subject 的 Logout() 方法.
System.out.println("---->" + currentUser.isAuthenticated());
//登出
currentUser.logout();
System.out.println("---->" + currentUser.isAuthenticated()); System.exit(0);
}
}

shiro-helloworld的更多相关文章

  1. 第一节:Shiro HelloWorld 实现

    1.新建maven工程,pom配置maven jar包 <dependency> <groupId>org.apache.shiro</groupId> <a ...

  2. Shiro学习

    Shiro学习资源 Shiro官网,http://shiro.apache.org/index.html 学习网站链接,http://blog.java1234.com/blog/articles/4 ...

  3. shiro(安全框架)

    shiro.apache.org JavaSE环境搭建Shiro框架 1/导入与 shiro相关的Jar包 所有集好的环境可以在如下目录查找 复制如上文件到工程中 2/配置文件:储存临时文件 shir ...

  4. Shiro-HelloWord

    HelloWorld Shiro的HelloWorld不是我们写的,而是看Shiro给我们提供的一段代码.通过这段代码可以看到Shiro大致的使用方式. 1.找到Shiro的jar包 目前的最新稳定版 ...

  5. shiro-core包引用的版本问题

    在做shiro学习时,遇到这样的问题: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/ ...

  6. Shrio第一天——入门与基本概述

    一.Shiro是什么 Apache Shiro是Java的一个安全框架.(希罗:/笑哭) Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境. sh ...

  7. Shrio Demo

    package com.atguigu.shiro.helloworld; import org.apache.shiro.SecurityUtils; import org.apache.shiro ...

  8. Shiro 的 HelloWorld

    密码文件 [users] zhang=123 wang=123 测试 package org.zln.hello; import org.apache.log4j.LogManager; import ...

  9. shiro的Helloworld

    package shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePassword ...

  10. Shiro 加密helloWorld

    承接第一章 初解加密 只贴更改的源码,其他看上一篇. ShiroRealm.java package com.lkk.shiro.realms; import org.apache.shiro.aut ...

随机推荐

  1. python遍历多个列表生成列表或字典

    key=['a','b','c','d'] value=[1,2,3,4] mydict=dict(zip(key,value)) print mydict 输出结果: {'a': 1, 'c': 3 ...

  2. Android短视频中如何实现720P磨皮美颜录制?

    视频中磨皮.美颜功能已成为刚需,那么如何在Android短视频中实现720P磨皮美颜录制?本篇文章中,网易云信资深开发工程师将向大家介绍具体的操作方法. 相关阅读推荐 <短视频技术详解:Andr ...

  3. EditPlus 格式化HTML JS CSS

    首先你得安装一个EditPlus,然后下载你想格式化的xxxformatter.js文件,也就是网上说的EDTOOLS 1.在你的工具里边找到-->配置自定义工具 具体做法如下: 第5步 命令: ...

  4. J2SE的基本简介与J2EE/J2ME的差异

    J2SE简介与J2EE.J2ME的比较 Java2平台包括:标准版(J2SE).企业版(J2EE)和微缩版(J2ME)三个版本. J2SE,J2ME和J2EE,这也就是SunONE(Open NetE ...

  5. 并发编程-concurrent指南-回环栅栏CyclicBarrier

    字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行. java.util.concurrent.CyclicBarrier 类是一种同步机制,它能够对处理一些算法的线程实现同步 ...

  6. 微信支付重复回调,java微信支付回调问题

    这几天一直在研究微信支付回调这个问题,发现之前微信支付回调都是正常的也没怎么在意,今天在自己项目上测试的时候发现相同的代码在我这个项目上微信支付回调老是重复执行导致支付成功之后的回调逻辑一直在执行,很 ...

  7. 测试调试-利用fiddler修改response返回结果

    测试前端过程中,经常需要验证各种功能状态.不同数据层级等返回后的展示效果.一般会通过以下三种方式进行测试: 1.构造满足条件的测试数据:(耗时费力) 2.修改数据库:(前提需要了解数据库数据存储.沟通 ...

  8. 初识Grep

    前言:grep这个命令都不陌生,最常用的就是和管道符结合,例如:ps -ef | grep docker,但是我还是想认识一下这个非常giao的命令... Grep称为全局正则表达式检索工具,在企业中 ...

  9. Greenplum主备节点切换

    1. 场景描述 Greenplum主节点出现故障,需要将standby节点手动切换为master节点,当master节点修复完成后,再将新修复的master节点设置为standyb节点加入到集群中. ...

  10. 剑指offer第二版-10.斐波那契数列

    面试题10:斐波那契数列 题目要求: 求斐波那契数列的第n项的值.f(0)=0, f(1)=1, f(n)=f(n-1)+f(n-2) n>1 思路:使用循环从下往上计算数列. 考点:考察对递归 ...