shiro-helloworld
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的更多相关文章
- 第一节:Shiro HelloWorld 实现
1.新建maven工程,pom配置maven jar包 <dependency> <groupId>org.apache.shiro</groupId> <a ...
- Shiro学习
Shiro学习资源 Shiro官网,http://shiro.apache.org/index.html 学习网站链接,http://blog.java1234.com/blog/articles/4 ...
- shiro(安全框架)
shiro.apache.org JavaSE环境搭建Shiro框架 1/导入与 shiro相关的Jar包 所有集好的环境可以在如下目录查找 复制如上文件到工程中 2/配置文件:储存临时文件 shir ...
- Shiro-HelloWord
HelloWorld Shiro的HelloWorld不是我们写的,而是看Shiro给我们提供的一段代码.通过这段代码可以看到Shiro大致的使用方式. 1.找到Shiro的jar包 目前的最新稳定版 ...
- shiro-core包引用的版本问题
在做shiro学习时,遇到这样的问题: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/ ...
- Shrio第一天——入门与基本概述
一.Shiro是什么 Apache Shiro是Java的一个安全框架.(希罗:/笑哭) Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境. sh ...
- Shrio Demo
package com.atguigu.shiro.helloworld; import org.apache.shiro.SecurityUtils; import org.apache.shiro ...
- Shiro 的 HelloWorld
密码文件 [users] zhang=123 wang=123 测试 package org.zln.hello; import org.apache.log4j.LogManager; import ...
- shiro的Helloworld
package shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePassword ...
- Shiro 加密helloWorld
承接第一章 初解加密 只贴更改的源码,其他看上一篇. ShiroRealm.java package com.lkk.shiro.realms; import org.apache.shiro.aut ...
随机推荐
- 对SpringMVC架构进行工程拆分遇到的问题总结
经过一个月的开发,一个单一的SpringMVC教育类创业项目正式上线,随着时间的推移,业务流量逐渐增大,最近对这个单一的工程从零进行SOA分布式改造,改造包括dubbo改造,集成化部署.高可用集群,负 ...
- linux Apache设置https访问以及加载mod_ssl.so模块以及问题解决
开始之前的话: 1.配置好服务器防火墙的443端口规则: 2.购买好证书文件,我是沃通证书,准备好证书,这里不演示证书的购买和安装. 3.根据服务器类型下载文件,apache一共有4个文件 这里提供沃 ...
- 【Netty整理02-详细使用】Netty入门
重新整理版:https://blog.csdn.net/the_fool_/article/details/83002152 参考资料: 官方文档:http://netty.io/wiki/user- ...
- php抽奖概率程序
抽奖概率思想: 1.给每一个奖项设置要给概率数,如下面所有奖品综合设置为100,iphone5s是5,也就是5% 2.然后通过php生成随机数函数生成一个在总概率之间的随机数 如:抽第一个奖品5s的时 ...
- Visual Studio Code配置
Visual Studio Code 从1.23.0开始VS Code就不再默认提供各语言版本, 而是改为使用插件的方式提供语言包. 在插件商店搜索Chinese (Simplified), 安装. ...
- STM32 HAL库学习系列第7篇---定时器TIM 输入捕获功能
测量脉冲宽度或者测量频率 基本方法 1.设置TIM2 CH1为输入捕获功能: 2.设置上升沿捕获: 3.使能TIM2 CH1捕获功能: 4.捕获到上升沿后,存入capture_buf[0], ...
- 一个简易的css reset
/*css reset*/ /*清除内外边距*/ body, h1, h2, h3, h4, h5, h6, p, hr, /*结构元素*/ ul, ol, li, dl, dt, dd, /*列表元 ...
- 半小时学会V语言
半小时学会V语言 1. V语言简介 V是一个静态类型.编译型的编程语言,目标是构建可维护软件.与Go语言相似,并受Oberon,Rust和Swift语言影响.V语言非常简单,只需要半小时就能学会这门语 ...
- Java日志脱敏框架 sensitive-v0.0.4 系统内置常见注解,支持自定义注解
项目介绍 日志脱敏是常见的安全需求.普通的基于工具类方法的方式,对代码的入侵性太强.编写起来又特别麻烦. 本项目提供基于注解的方式,并且内置了常见的脱敏方式,便于开发. 特性 基于注解的日志脱敏. 可 ...
- python爬虫之快速对js内容进行破解
python爬虫之快速对js内容进行破解 今天介绍下数据被js加密后的破解方法.距离上次发文已经过去半个多月了,我写文章的主要目的是把从其它地方学到的东西做个记录顺便分享给大家,我承认自己是个懒猪.不 ...