欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

第一节:Shiro HelloWorld 实现

程序员文章站 2023-11-02 15:57:52
1、新建maven工程,pom配置maven jar包 org.apache.shiro shiro-core 1.2.4

1、新建maven工程,pom配置maven jar包

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

2.resourses下新建文件配置shiro.ini,配置如下

[users]
java1234=123456
jack=123

3.resourses下新建文件配置log4g.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.新建class文件helleworld.java

​package com.slix.shiro;

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

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("java1234", "123456");
try{
// 身份认证
currentuser.login(token);
system.out.println("身份认证成功!");
}catch(authenticationexception e){
e.printstacktrace();
system.out.println("身份认证失败!");
}
// 退出
currentuser.logout();
}
}