博客详情

shiro身份认证过程 (原创)

作者: 朝如青丝暮成雪
发布时间:2019-03-25 08:03:05  文章分类:shiro   阅读(903)  评论(0)

一、shiro身份认证过程

(参考http://shiro.apache.org/authentication.html)

1、Collect the Subject’s submitted principals and credentials  收集客户端提交的用户名和凭证

2、Submit the principals and credentials for authentication.      提交用户名和凭证进行身份认证  
3、If the submission is successful, allow access, otherwise retry authentication or block access.  如果提交成功,则允许访问,否则重试身份验证或阻止访问。



二、java示例代码

pom.xml :


<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.tingcream</groupId>
  <artifactId>shiro</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>shiro</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
    </dependency>

    <!-- shiro-core 引入 -->
	<dependency>
	    <groupId>org.apache.shiro</groupId>
	    <artifactId>shiro-core</artifactId>
	    <version>1.3.2</version>
	</dependency>
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-log4j12</artifactId>
	    <version>1.7.21</version>
    </dependency>
    
  </dependencies>
  <build>
    <plugins>
       <plugin>
	     <groupId>org.apache.maven.plugins</groupId>
	     <artifactId>maven-compiler-plugin</artifactId>
	     <version>3.6.2</version>
	     <configuration>
	        <target>1.8</target>   
	        <source>1.8</source>
	        <encoding>utf-8</encoding>
	     </configuration>
	  </plugin>
    </plugins>
  </build>
</project>



HelloWorld.java


package com.tingcream.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
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.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * shiro认证过程 ,使用shiro.ini配置文件
 * @author jelly
 */
public class HelloWorld {

	public static void main(String[] args) {
		// 读取配置文件,初始化SecurityManager工厂
		Factory 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("zhangsan", "zs123456");

		//”Remember Me” built-in, just do this: 
		//token.setRememberMe(true);
		try {
		    currentUser.login(token);
		    System.out.println("用户身份认证成功!");
		} catch  ( UnknownAccountException e ) { 
			  e.printStackTrace();
			 System.out.println("未知的账户,用户名不存在");
		} catch  ( IncorrectCredentialsException e ) {
			 e.printStackTrace();
			 System.out.println("密码错误");
		} catch  ( LockedAccountException e ) { 
			  e.printStackTrace();
			 System.out.println("账户被锁定");
			
		} catch  ( ExcessiveAttemptsException e ) { 
			  e.printStackTrace();
			  System.out.println("过度的尝试");
			
		}   catch ( AuthenticationException e ) {
			  e.printStackTrace();
			  System.out.println("认证失败");
		}
		currentUser.logout();
	}
}


log4j.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
shiro.ini


[users]
zhangsan=zs123456
lisi=ls123456

注意:

运行main方法,若用户登录成功(用户名、密码正确),则打印用户身份认证成功。若失败,shiro会以抛出各种内置异常的方式给予反馈。所以我们需要在try...catch块中捕获各种类型的异常。

关键字:  shiro  authentication

上一篇:shiro入门-第一篇

下一篇:shiro授权过程

评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号