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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值