Shiro是一个强大灵活的开源安全框架,提供身份验证、授权、会话管理、密码体系。

1.先创建一个Maven项目

2.配置pom

<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
             http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.stu</groupId>
<artifactId>shiro-test</artifactId>
<version>0.0.1-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency> </dependencies> </project>

3.在src/main/java下创建log4j.properties文件,配置logger

log4j.rootLogger=info, ServerDailyRollingFile, stdout
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=C://logs/notify-subscription.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d - %m%n
log4j.appender.ServerDailyRollingFile.Append=true log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n

4.在根目录下创建auth.ini文件

[users]
lonestarr = vespa

5.示例代码

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.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 ShiroTest { private static Logger logger = LoggerFactory.getLogger(ShiroTest.class); public static void main(String[] args) {
Factory<org.apache.shiro.mgt.SecurityManager> factory =
               new IniSecurityManagerFactory("auth.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager); //obtain the currently executing user
Subject user = SecurityUtils.getSubject(); //logger.info("User is authenticated: " + user.isAuthenticated()); /*The Session is a Shiro-specific instance that provides most of
* what you're used to with regular HttpSessions but with some
* extra goodies and one big difference: it does not require
* an HTTP environment!
*/
Session session = user.getSession();
session.setAttribute("key", "value"); if(!user.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
user.login(token);
//if no exception, that's it, we're done!
} catch (UnknownAccountException uae) {
//username wasn't in the system, show them an error message?
} catch (IncorrectCredentialsException ice ) {
//password didn't match, try again?
} catch (LockedAccountException lae) {
//account for that username is locked - can't login. Show them a message?
}
//... more types exceptions to check if you want ...
catch (AuthenticationException ae) {
//unexpected condition - error?
}
} //get user name
logger.info( "User [" + user.getPrincipal() + "] logged in successfully." ); //if user have specific role or not
if(user.hasRole("schwartz")) {
logger.info("May the Schwartz be with you!");
}
else {
logger.info( "Hello, mere mortal.");
} //we can perform an extremely powerful instance-level permission
//check - the ability to see if the user has the ability to access
//a specific instance of a type
if (user.isPermitted("winnebago:drive:eagle5" ) ) {
logger.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'." +
"Here are the keys - have fun!");
} else {
logger.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
} // when the user is done using the application, they can log out
user.logout();
} }

6.运行结果

2016-08-04 15:27:48 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] Enabling session validation scheduler...
2016-08-04 15:27:48 INFO [cn.edu.stu.shiro.ShiroTest] User [lonestarr] logged in successfully.
2016-08-04 15:27:48 INFO [cn.edu.stu.shiro.ShiroTest] Hello, mere mortal.
2016-08-04 15:27:48 INFO [cn.edu.stu.shiro.ShiroTest] Sorry, you aren't allowed to drive the 'eagle5' winnebago!

Apache Shiro入门实例的更多相关文章

  1. Apache Mina入门实例

    一.mina是啥 ApacheMINA是一个网络应用程序框架,用来帮助用户简单地开发高性能和高可扩展性的网络应用程序.它提供了一个通过Java NIO在不同的传输例如TCP/IP和UDP/IP上抽象的 ...

  2. shiro入门实例,基于ini配置

    基于ini或者关系数据库的,其实都是一样的,重要的是思想. # ==================================================================== ...

  3. spring+mybatis+shiro入门实例

    sql: 1 /* 2 SQLyog Ultimate v11.33 (64 bit) 3 MySQL - 5.1.49-community : Database - db_shiro 4 ***** ...

  4. Apache Mina 入门实例

    这个教程是介绍使用Mina搭建基础示例.这个教程内容是以创建一个时间服务器. 以下是这个教程需要准备的东西: MINA 2.0.7 Core JDK 1.5 或更高 SLF4J 1.3.0 或更高 L ...

  5. Apache Shiro系列三,概述 —— 10分钟入门

     一.介绍 看完这个10分钟入门之后,你就知道如何在你的应用程序中引入和使用Shiro.以后你再在自己的应用程序中使用Shiro,也应该可以在10分钟内搞定. 二.概述 关于Shiro的废话就不多说了 ...

  6. Apache shiro集群实现 (一) shiro入门介绍

    近期在ITOO项目中研究使用Apache shiro集群中要解决的两个问题,一个是Session的共享问题,一个是授权信息的cache共享问题,官网上给的例子是Ehcache的实现,在配置说明上不算很 ...

  7. Apache Shiro 快速入门教程,shiro 基础教程

    第一部分 什么是Apache Shiro     1.什么是 apache shiro :   Apache Shiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理 ...

  8. Shiro学习总结(2)——Apache Shiro快速入门教程

    第一部分 什么是Apache Shiro 1.什么是 apache shiro : Apache Shiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理 如同 spr ...

  9. Apache Shiro 1.3.2入门

    简介 Apache Shiro是一个功能强大且灵活的开放源代码安全框架,可以清楚地处理认证,授权,企业会话管理和加密.Apache Shiro的首要目标是易于使用和理解.有时候安全性可能非常复杂和痛苦 ...

随机推荐

  1. python ssh弱口令爆破多线程脚本及遇到的一些错误与问题

    练习写了个SSH弱口令爆破多线程脚本,遇到的问题 1.一开始想import pexpect 中的pxssh 然而却一直该有错误, ImportError: cannot import name spa ...

  2. 一个使用CDS VIEW 的 DEMO

    一个使用CDS VIEW 的demo REPORT demo_cds_currency_conversion. CLASS demo DEFINITION. PUBLIC SECTION. CLASS ...

  3. Codeforces Codeforces Round #319 (Div. 2) B. Modulo Sum 背包dp

    B. Modulo Sum Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/577/problem/ ...

  4. C# 网络编程之豆瓣OAuth2.0认证具体解释和遇到的各种问题及解决

            近期在帮人弄一个豆瓣API应用,在豆瓣的OAuth2.0认证过程中遇到了各种问题,同一时候自己须要一个个的尝试与解决,终于完毕了豆瓣API的訪问.作者这里就不再吐槽豆瓣的认证文档了,毕 ...

  5. Microsoft Visual Studio与Firefly 加载的项目已建议,更新源代码地位问题

    一开始装笔记本vs2010,由于使用的近期发展vs2008与vs2005所以,今天再次2008.2005安装在,但是在打开的项目时,,首先提示加载项目文件.然后已建议状态,非常慢非常慢的,之前仅仅有v ...

  6. iOS开发——UI篇OC篇&UIDynamic详解

    iOS开发拓展篇—UIDynamic(简单介绍) 一.简单介绍 1.什么是UIDynamic UIDynamic是从iOS 7开始引入的一种新技术,隶属于UIKit框架 可以认为是一种物理引擎,能模拟 ...

  7. [WebGL入门]二,開始WebGL之前,先了解一下canvas

    年2月)HTML5依旧处于草案阶段. HTML5支持网页端的多媒体功能和画布功能,追加了非常多全新的更合理的Tag标签.各个浏览器也都在逐渐的完好这些新的特性. Canvas对象表示一个 HTML画布 ...

  8. android131 360 05 手势触摸滑动,sim卡,开机启动的广播,手机联系人,SharedPreferences,拦截短信

    安卓手势触摸滑动: package com.itheima52.mobilesafe.activity; import android.app.Activity; import android.con ...

  9. 可视化swing界面编辑--转载

    原文地址:http://279234058.iteye.com/blog/2200122 今天发现了一个WindowBuilder插件,功能好强大,啊哈哈,从此告别手动编辑swing界面代码,直接像V ...

  10. linux剪切拷贝

    1.剪切 mv rename.sh  ../rename.sh  把这个文件移到上一级目录下 mv rename.sh ./pic/rename.sh 把这个文件移到 当前目录下的pic目录下,并改名 ...