shiro(三)——认证、MD5加密、多Realm验证

代码接着之前文章的进行。

首先表单页面:包含用户名密码:只是为了实现功能,就不细究页面的美观了。。

<form action="shiro/login" method="POST">
	username:<input type="text" name="username"/>
	<br><br>
	password:<input type="password" name="password"/>
	<br><br>
	<input type="submit" value="submit"/>
</form>

写一个Controller类:细节方面都在代码注释中

package com.znx.shiro.handlers;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {
	
	@RequestMapping("/login")
	public String login(@RequestParam("username")String username,
			@RequestParam("password")String password) {
		
		//获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		
		if(!currentUser.isAuthenticated()){
			//把用户名和密码封装为UsernamePasswordToken对象
			UsernamePasswordToken  token = new  UsernamePasswordToken(username,password);
			//rememberme
			token.setRememberMe(true);
			try{
				//执行登录
				currentUser.login(token);
			}catch(AuthenticationException ae){
				System.out.println("登录失败"+ae.getMessage());
			}
		}		
		return "redirect:/list.jsp";		
	}	
}

实现自定义的Realm类:

package com.znx.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.Realm;

public class ShiroRealm extends AuthenticatingRealm{
	

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		//1.把AuthenticationToken 转换为UsernamePasswordToken
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		//2.从UsernamePasswordToken中获取Username
		String username = upToken.getUsername();
		//3.调用数据库的方法,从数据库中查询username对应的用户记录
		System.out.println("从数据库中获取username"+username+"所对应的用户信息");
		//4.若用户不存在,则可以抛出UNknowAccountException异常
		if("unknown".equals(username)){
			throw new UnknownAccountException("用户不存在");
		}
		//5.根据用户信息的情况,决定是否需要抛出其他异常
		if("monster".equals(username)){
			throw new LockedAccountException("用户被锁定");
		}
		//6.根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用的实现类是SimpleAuthenticationInfo
		//以下信息是从数据库中获取的
		//1):principal:认证的实体信息,可以是username,也可以是数据库表对应的用户的实体类对象
		Object principal = username;
		//2):credentials:密码
		Object  credentials = "123456";
		//3):realmName:当前realm对象的name,调用父类的getName()方法即可
		String realmName = getName();
		SimpleAuthenticationInfo  info = new SimpleAuthenticationInfo(principal, credentials,realmName);
		 		
		return info;
	}


}

代码就基本上写完了,启动工程:

 输入错误的用户名:登录失败:

 输入正确的话,会跳转到登录成功的页面。

 在list.jsp页面中添加了一个退出的操作。

<a href="shiro/logout">logout</a>

下一步只需要在applicationContext.xml中声明即可

 但是,用户的密码一般是不会以明文的形式直接存储在数据库中的,常用的加密方式为MD5加密。Shiro也提供了这样的支持。

配置文件中进行配置:

  <bean id="jdbcRealm" class="com.znx.shiro.realms.ShiroRealm">
    	<property name="credentialsMatcher">
    		<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    				<property name="hashAlgorithmName" value="MD5"></property>
    				<!-- 加密次数 -->
    				<property name="hashIterations" value="1024"></property>
    		</bean>
    	</property>
    </bean>

重启工程,是可以登录成功的。

上面的加密是没有加盐值的,那么如果两个人的明文密码一样,加密后的字符串也是一样的了,这时候就应该加salt来解决这种问题。这里就对之前的代码进行一些修改:
 

//4).盐值
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		SimpleAuthenticationInfo  info =null;
		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,realmName);
		 		
		return info;

运行程序,进行访问,是没有问题的,这里就不贴结果了,贴一下这个类的全部代码:

package com.znx.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.ByteSource;

public class ShiroRealm extends AuthenticatingRealm{
	

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		//1.把AuthenticationToken 转换为UsernamePasswordToken
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		//2.从UsernamePasswordToken中获取Username
		String username = upToken.getUsername();
		//3.调用数据库的方法,从数据库中查询username对应的用户记录
		System.out.println("从数据库中获取username"+username+"所对应的用户信息");
		System.out.println(username+"+++MD5");
		//4.若用户不存在,则可以抛出UNknowAccountException异常
		if("unknown".equals(username)){
			throw new UnknownAccountException("用户不存在");
		}
		//5.根据用户信息的情况,决定是否需要抛出其他异常
		if("monster".equals(username)){
			throw new LockedAccountException("用户被锁定");
		}
		//6.根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用的实现类是SimpleAuthenticationInfo
		//以下信息是从数据库中获取的
		//1):principal:认证的实体信息,可以是username,也可以是数据库表对应的用户的实体类对象
		Object principal = username;
		//2):credentials:密码
		Object  credentials =null;
		if("admin".equals(username)){
			//自己通过算法模拟数据库的数据
			credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
		}else if("user".equals(username)){
			//自己通过算法模拟数据库的数据
			credentials="098d2c478e9c11555ce2823231e02ec1";
		}
		
		
		//3):realmName:当前realm对象的name,调用父类的getName()方法即可
		String realmName = getName();
		//4).盐值
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		SimpleAuthenticationInfo  info =null;
		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,realmName);
		 		
		return info;
	}
	

}

MD5盐值加密就介绍到这里了。

多Realm验证:

继续。将之前的Realm复制一份为SecondRealm,将加密方式改为SHA1,并在applicationContext.xml中配置。

package com.znx.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.ByteSource;

public class SecondRealm extends AuthenticatingRealm{
	

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		System.out.println("SecondRealm----------doGetAuthenticationInfo");
		
		//1.把AuthenticationToken 转换为UsernamePasswordToken
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		//2.从UsernamePasswordToken中获取Username
		String username = upToken.getUsername();
		//3.调用数据库的方法,从数据库中查询username对应的用户记录
		System.out.println("从数据库中获取username"+username+"所对应的用户信息");
		System.out.println(username+"+++MD5");
		//4.若用户不存在,则可以抛出UNknowAccountException异常
		if("unknown".equals(username)){
			throw new UnknownAccountException("用户不存在");
		}
		//5.根据用户信息的情况,决定是否需要抛出其他异常
		if("monster".equals(username)){
			throw new LockedAccountException("用户被锁定");
		}
		//6.根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用的实现类是SimpleAuthenticationInfo
		//以下信息是从数据库中获取的
		//1):principal:认证的实体信息,可以是username,也可以是数据库表对应的用户的实体类对象
		Object principal = username;
		//2):credentials:密码
		Object  credentials =null;
		if("admin".equals(username)){
			//自己通过算法模拟数据库的数据
			credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
		}else if("user".equals(username)){
			//自己通过算法模拟数据库的数据
			credentials="073d4c3ae812935f23cb3f2a71943f49e082a718";
		}	
		//3):realmName:当前realm对象的name,调用父类的getName()方法即可
		String realmName = getName();
		//4).盐值
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		SimpleAuthenticationInfo  info =null;
		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,realmName);
		 		
		return info;
	}
	
	public static void main(String[] args) {
		
		String hashAlgorithmName  = "SHA1";
		Object credentials = "123456";
		Object salt = ByteSource.Util.bytes("admin");
		int hashIterations = 1024;
		Object result = new SimpleHash(hashAlgorithmName, credentials, salt,hashIterations);
		System.out.println(result);		
	}
}

applicationContext.xml中:

先增加一个realm:

 <bean id="secondRealm" class="com.znx.shiro.realms.SecondRealm">
    	<property name="credentialsMatcher">
    		<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    				<property name="hashAlgorithmName" value="SHA1"></property>
    				<!-- 加密次数 -->
    				<property name="hashIterations" value="1024"></property>
    		</bean>
    	</property>
    </bean>

再配置一个认证器,将这个realm与之前的realm配置进去:

   <!-- 认证器 -->
    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
    	<property name="realms">
    		<list>
    			<ref bean ="jdbcRealm" />
    			<ref bean ="secondRealm"/>
    		</list>
    	</property>
    </bean>

最后,在SecurityManager中配置认证器:

   <!-- 1.配置SecurityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="authenticator" ref="authenticator"/>
    </bean>

启动项目,访问。发现两个Realm都走了一遍。

这里有两个Realm,是怎样认证成功的呢?就是接下来要说的认证策略。

认证策略实际上是一个接口:AuthenticationStrategy。

这个接口默认有三个实现:

1.FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功的认证信息,其他的忽略。

2.AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同:将返回所有Realm身份验证成功的认证信息。

3.AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。

ModularRealmAuthenticator默认是AtLeastOneSuccessfulStrategy策略;

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值