初识Shiro

初识shiro

  Shiro是一个Java安全框架,提供了认证、授权、加密和会话管理功能,可以为任何应用提供安全保障。

使用shiro

  1.添加shiro相关jar包(使用maven添加依赖)

  <!-- shiro begin -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.2.4</version>
    </dependency>
    <!-- shiro end -->
    
    <!-- slf4j begin -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
    </dependency>
    <!-- slf4j end -->

  2.在项目resources下新建一个shiro.ini文件方便测试 

[users]
zhen=123
jack=jack

  3.新建测试文件

package com.zhen.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 HelloWorld {

    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("zhen", "123");
        try {
            //身份认证
            currentUser.login(token);
            System.out.println("身份认证成功!");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("身份认证失败!");
        }
        //退出
        currentUser.logout();
        
    }

}

 

  

posted on 2017-02-20 21:46  嘣嘣嚓  阅读(297)  评论(0编辑  收藏  举报

导航