当前位置: 首页 > 编程日记 > 正文

java shiro实例_Apache Shiro入门实例

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

b7a5a6bb81389f0342be53d85426966e.png

1.先创建一个Maven项目

2.配置pom

http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

cn.edu.stu

shiro-test

0.0.1-SNAPSHOT

org.apache.shiro

shiro-core

1.3.0

org.slf4j

slf4j-log4j12

1.6.4

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) {

Factoryfactory =

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!

相关文章:

采购申请-MRP

1、手工建立采购申请: ME51N 申请单建立的时候,在不知道给哪个部门使用的时候可以在科目指派中选择U 分配并处理采购申请:me57 A:首先分配供应商 B:在转换成PO 点自动分配-》点分配-》点处理分配完成PR转变成PO 2、MRP 首先要建立BOM,然后在建…

【C语言】07-预处理指令;-宏定义

预处理指令简介; 1,C在对源程序进行编译之前,会对一些特殊的预处理指令作解释,产生一个新的源程序,此过程叫做编译预处理.C在经过编译预处理之后才对新的源码进行通常的编译; 2,预处理以‘#’开头,且结尾不用分号,(用于和一般的C语句区分开来). 3,预处理指令可以出现在出现的任…

idea基于hibernate生成的Entitle对象,会忽略外键属性

需要自己手动添加 如 private String cgcode;BasicColumn(name "cgcode")public String getCgcode() {return cgcode;}public void setCgcode(String cgcode) {this.cgcode cgcode;} 转载于:https://www.cnblogs.com/asusdell/p/10482657.html

编程模式 之美 -- 抽象工厂模式

文章目录1. 解决问题2. 应用场景3. 实现如下:C实现C语言实现4. 缺点1. 解决问题 在工厂方法模式中,我们卖衣服。此时我们为每一种衣服创建不同的工厂,帽子有一个工厂专门创建,裤子有一个工厂专门创建,T恤有一个工厂专…

java map class_java – 将通用Class参数限制为实现Map的类

我正在尝试编写一个Map构建器.其中一个构造函数将允许客户端指定他们希望构建的Map类型public class MapBuilder {private Map map;/*** Create a Map builder* param mapType the type of Map to build. This type must support a default constructor* throws Exception*/pub…

双击进入物料数据的指定视图

SET PARAMETER ID MAT FIELD i_matnr-matnr.“物料号SET PARAMETER ID MXX FIELD K. 进入基本视图 "Table T132CALL TRANSACTION MM03 AND SKIP FIRST SCREEN. MXX 可以在后台查看: SPRO->后勤系统-一般->物料主档->设定物料主档->…

java中Integer装箱的注意

Integer inb 2;//自动装箱 Integer inc 2; System.out.println(inb inc );//输出true Integer biga 128; Integer bigb 128; System.out.println(biga bigb);//输出false上面的代码来自李刚老师的书,应该注意其中的细节.上面的输出与Integer的设计有关。1.系统…

rem自适应js

Rem自适应js---flexible.min.js 网上看到很多移动端适配的各种方法,由于原来工作中对rem的疏忽,所以决定重新学习rem~ 由于移动端特殊性,本文讲的是如何使用rem实现自适应,或叫rem响应式布局,通过使用一个脚本就可以re…

设计模式 之美 -- 建造者模式

文章目录1. 解决问题2. 应用场景3. 实现C语言实现C实现4. 缺点1. 解决问题 描述如下场景: 类的数据成员很多(8个以上),当我们进行初始化的时候放在初始化列表中,影响类的可读性,同时校验初始化参数列表是…

dateformat java 并发_java.text.DateFormat 多线程并发问题

在日常开发中,java.text.DateFormat 应该算是使用频率比较高的一个工具类,经常会使用它 将 Date 对象转换成字符串日期,或者将字符串日期转化成 Date 对象。先来看一段眼熟的代码:类 DateUtils 的方法 formatForDay() 在多线程的情…

每天一个摆脱if-else工程师的技巧——优雅的参数校验

在日常的开发工作中,为了程序的健壮性,大部分方法都需要进行入参数据校验。最直接的当然是在相应方法内对数据进行手动校验,但是这样代码里就会有很多冗余繁琐的if-else。throw new IllegalArgumentException("用户姓名不能为空");throw new IllegalArgumentException("性别不能为空");throw new IllegalArgumentException("性别错误");

我下载的最新的linux ADT+eclipse中没有NDK

问题描述我下载的是 adt-bundle-linux-x86_64-20140702.zip 这个版本。我已经安装了CDT了,但是还是没有NDK可以设置,而且在project右键android tools下 没有Add Native Support这个选项求指教,谢谢! 解决方案1你的Eclipse插件好…

Android中去掉标题的方法总结

方法一:也一般入门的时候经常使用的一种方法在setContentView()方法的前面插入代码: requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 package com.example.helloword;import android.os.Bundle; import android.app.Activity; import and…

ImportError: No localization support for language ‘eng’ in python

ImportError: No localization support for language ‘eng’ in python 遇到這一個問題,是因為有缺少檔案,我是因為使用 pyinstaller 去包裝執行檔,所以需要手動加入這一個設定值進 .spec 檔案裡: hiddenimports[mysql,mysql.con…

C++ 智能指针(unique_ptr / shared_ptr)代码实现

文章目录unique_ptr 智能指针的实现shared_ptr 智能指针的实现指针类型转换unique_ptr 智能指针的实现 一个对象只能被单个unique_ptr 所拥有。 #include <iostream>using namespace std;/*增加模板类型&#xff0c;保证智能指针的类型是由传入的类型决定的*/ template…

winform实现截图

这个截图模仿QQ截图&#xff0c;左键单击开始截图&#xff0c;鼠标移动出现方框确定截图尺寸&#xff0c;放开时为最终尺寸&#xff0c;双击鼠标弹出保存对话框进行保存。 还有一点就是&#xff0c;如果截图尺寸方框已经确定&#xff0c;移动鼠标到所选区域内时&#xff0c;鼠标…

java interface list_你了解注解内的@interface List么

Annotation, Multi-valued annotation, nested annotation, 多值注解, 嵌套注解今天在研究Spring MVC的Validation机制时(这里 | 还有这里)&#xff0c;简单看了下一些注解的源码&#xff0c;比如Min&#xff0c;发现以前从来没注意到的注解写法。看来基础知识有疏漏啊.../*** …

Struts 2的输入校验(一)

9 Struts 2的输入校验输入校验有两种&#xff1a;客户端和服务器端校验。客户端校验一般是通过JavaScript来完成&#xff0c;这种校验可减轻服务器压力。服务器校验主要通过服务器端编程的方式来完成。(1) 客户端校验客户端校验一般是通过JavaScript来完成&#xff0c;这种校验…

通过document.domain实现跨域访问

通过document.domain实现跨域访问&#xff1a;https://blog.csdn.net/nlznlz/article/details/79506655 前端跨域方法之document.domain和location.hash&#xff1a;https://blog.csdn.net/WEB_YH/article/details/79364565 转载于:https://www.cnblogs.com/bydzhangxiaowei/p/…

设计模式 之美 -- 原型模式

文章目录1. 解决问题2. 应用场景3. 实现方式C实现C语言实现4. 缺点5. 和其他三种创建模式的对比&#xff08;单例&#xff0c;工厂&#xff0c;建造者&#xff09;1. 解决问题 如果对象的创建成本较大&#xff0c;而同一个类的不同对象之间的差别不大&#xff08;大部分字段相…

Objective-C语法简记

开始学习iPhone开发了&#xff0c;虽然现在已经有了Swift&#xff0c;但我还是老老实实地学习Objective-C&#xff0c;鄙人入门的程序语言是C&#xff0c;后来学习了C#和Java&#xff0c;现在来学Objective-C&#xff0c;这篇只是一些很简略的笔记&#xff0c;不算是语法书。 代…

java编写最大公约数_Java编写最大公约数和最小公倍数

package javaapplication24;class NegativeIntegerException extends Exception{String message;public NegativeIntegerException(){message"方法的参数值不是正整数";}public String toString(){return message;}}class MaxCommonDivisor{public int getMaxCommonD…

肤色检测算法 - 基于不同颜色空间简单区域划分的皮肤检测算法

由于能力有限&#xff0c;算法层面的东西自己去创新的很少&#xff0c;很多都是从现有的论文中学习&#xff0c;然后实践的。 本文涉及的很多算法&#xff0c;在网络上也有不少同类型的文章&#xff0c;但是肯定的一点就是&#xff0c;很多都是不配代码的&#xff0c;或者所附带…

【算法学习】堆排序建立最大堆

本文代码均转自&#xff1a; 作者&#xff1a;早就戒了 来源&#xff1a;CSDN 原文&#xff1a;https://blog.csdn.net/qq_37169817/article/details/79777264 版权声明&#xff1a;本文为博主原创文章&#xff0c;转载请附上博文链接&#xff01; 1 public class HeapSort { 2…

设计模式 之美 -- 代理模式

文章目录1. 解决问题2. 应用场景1. 业务系统的非功能性开发2. 代理模式在RPC、缓存中的应用3. 实现C实现C语言实现1. 解决问题 客户端和目标对象之间需要进行交互&#xff0c;此时客户端类和目标对象类相关操作之间的逻辑如果交合在一起&#xff0c;会导致客户端和目标对象模块…

java中注解的使用_java中注解的使用

使用过ssh框架的人一定也使用过注解&#xff0c;尤其是在spring框架中&#xff0c;注解可谓是spring容器和AOP编程的重要环节。注解就是用于修饰类、全局变量、方法、参数或局部变量的接口&#xff0c;java中规定&#xff0c;注解的使用不允许影响其修饰类的存在&#xff0c;也…

水题/poj 1852 Ants

1 /*2 PROBLEM:poj18523 AUTHER:Nicole4 MEMO:水题5 */6 #include<cstdio>7 using namespace std;8 int cmax(int a,int b){return a>b?a:b;}9 int cmin(int a,int b){return a<b?a:b;} 10 int main() 11 { 12 int cases; 13 scanf("%d…

素数、最大公约数、最下公倍数、质因数分解

2013-08-18 11:20:43 素数、最大公约数、最下公倍数、质因数分解都是与素数相关的&#xff0c;解决了素数的问题&#xff0c;其他的都可以此为基础求解。 小结&#xff1a; 求1到n之间的素数的基本方法是通过遍历2到sqrt(n)&#xff0c;判断每个数是否是素数来得到&#xff0c;…

Spring注解 开发

转载于:https://www.cnblogs.com/JBLi/p/10489541.html

读书:个人成长 -- 即兴演讲

与人交流时&#xff0c;有人发言语无伦次&#xff0c;舌头像打了结。 有人一开讲便滔滔不绝&#xff0c;却毫无重点。 也有人说话索然无味&#xff0c;没法让你投以关注。 如何在任何场合游刃有余地表达&#xff1f; 如何掌控此时此刻&#xff0c;用说话影响他人&#xff1f; …