Shiro学习笔记(1)--简单配置文件用户登录验证

1、以mavenproject方式创建一个简单的项目

2、在pom.xml中配置shiro所依赖的jar包

    <dependencies>
      <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
            </dependency>
            <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
    </dependency>

       </dependencies>

3、在resources中配置ini配置文件和log4j配置文件

shiro.ini

[users]
java1234=123456
jack=123

log4j.properties

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

4、创建验证类CurrentUserLogin.java文件,验证当前用户登录

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class CurrentUserLogin{
	public static void main(String[] args) {
		//读取配置文件,初始化SecurityManager工厂
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		//获取SecurityManager实例
		SecurityManager securityManager = factory.getInstance();
		//把SecurityManager实例绑定到SecurityUtils
		SecurityUtils.setSecurityManager(securityManager);
		//得到当前执行的用户
		Subject currentUser = SecurityUtils.getSubject();
		//创建token令牌,用户名/密码
		UsernamePasswordToken token = new UsernamePasswordToken("jack", "123");
		try {
			currentUser.login(token);
			System.out.println("身份认证成功!");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			System.out.println("身份认证失败!");
		}
		//退出
		currentUser.logout();
	}
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页