shiro
(java安全框架)
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
下面是hello word的简单实现
扫描二维码关注公众号,回复:
69611 查看本文章
接下来在pom.xml文件中添加shiro的核心包
<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>com.hp.shiro</groupId> <artifactId>Shiro</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Shiro</name> <description>Shiro</description> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.8.0-beta2</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> </dependencies> </project>
在src/main/resources里面添加登录需要的用户名与密码,由于是第一个hello word 没有连接数据库进行验证,如图
(注意的是 文件需要放在resources才能被读取)
package com.hp.hello; import org.apache.shiro.SecurityUtils; 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 HelloWord { public static void main(String[] args) { //读取配置文件 初始化SecurityManager工厂IniSecurityManagerFactory Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini"); //获得SecurityManager实例 SecurityManager instance = factory.getInstance(); //把SecurityManager的实例绑定到SecurityUtils上面 SecurityUtils.setSecurityManager(instance); //获取当前执行的用户 Subject subject = SecurityUtils.getSubject(); //创建token 令牌 用户名/密码 UsernamePasswordToken token=new UsernamePasswordToken("hello", "1123"); try{ //登录/身份认证 subject.login(token); System.out.println("身份认证成功..."); }catch(Exception e){ System.out.println("身份认证失败..."); } //退出 subject.logout(); } }
然后运行项目如图,看下输入错误
再把用户名密码改为正确的
其中还遇到一个bug ,log4j日志出不来,下次再解