一、SimpleAuthenticationInfo 简介
SimpleAuthenticationInfo 是 Shiro 框架的核心组件之一,用于封装身份验证信息,实现自定义的身份认证和授权逻辑,结合相关的 Realm 实现调用。它通过封装了认证成功后的用户身份信息、密码、盐等,来提供给 Realm 实现进行后续的授权验证。
二、SimpleAuthenticationInfo 的构造和方法
SimpleAuthenticationInfo 的构造方法如下:
SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName)
构造方法参数说明:
- principal:用户身份信息,通常为用户名或用户实体对象
- credentials:用户凭证,即密码或密码的密文
- hashedCredentials:加密后的用户凭证,即密码的密文
- credentialsSalt:密码加密的盐值,通常使用用户的唯一标识信息进行加密
- realmName:Realm 名称,即应用程序或系统唯一的 Realm 标识
SimpleAuthenticationInfo 中比较常用的方法如下:
Object getPrinicipal() Object getCredentials() Object getCredentialsSalt() String getRealmName()
三、SimpleAuthenticationInfo 的实现示例
下面以自定义的 Realm 实现为例,介绍 SimpleAuthenticationInfo 的具体使用方法:
1. Realm 实现示例
public class CustomRealm extends AuthorizingRealm { // 用于认证的方法 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 获取用户输入的用户名和密码 String userName = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); // 模拟数据库中的用户数据 if (!"admin".equals(userName)) { throw new UnknownAccountException(); // 没有找到账号 } if (!"123456".equals(password)) { throw new IncorrectCredentialsException(); // 密码错误 } // 创建 SimpleAuthenticationInfo 对象 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, password, getName()); // 返回 SimpleAuthenticationInfo 对象 return authenticationInfo; } // 用于授权的方法 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } }
2. 用户认证示例
// 获取当前操作的用户 Subject currentUser = SecurityUtils.getSubject(); // 创建一个身份验证 Token UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456"); // 身份认证 try { currentUser.login(token); System.out.println("身份认证成功"); } catch (UnknownAccountException e) { System.out.println("没有找到账户"); } catch (IncorrectCredentialsException e) { System.out.println("密码错误"); } catch (AuthenticationException e) { System.out.println("身份认证失败"); }
3. 密码加密示例
// 获取盐值 ByteSource salt = ByteSource.Util.bytes("admin"); // 获取加密后的密码 String newPassword = new SimpleHash("MD5", "123456", salt, 2).toHex(); System.out.println(newPassword);
四、SimpleAuthenticationInfo 的使用场景
SimpleAuthenticationInfo 主要用于自定义身份验证逻辑,可以结合相关的 Realm 实现进行调用。在大部分应用程序中,都需要对用户进行身份认证,而 SimpleAuthenticationInfo 提供了一种通用的方式,来封装身份认证所需的信息,从而简化了实现的复杂度,提高了程序的可扩展性和可维护性。
五、SimpleAuthenticationInfo 的注意事项
在使用 SimpleAuthenticationInfo 时需要注意以下几点:
- SimpleAuthenticationInfo 是线程安全的,可以在多个线程中共享使用。
- SimpleAuthenticationInfo 必须与 Realm 一起使用,否则将无法实现自定义的身份认证逻辑。
- 在进行用户身份认证时,强烈建议使用加密处理的密码,尤其是在实际应用中对密码进行存储时。
原创文章,作者:ORHL,如若转载,请注明出处:https://www.506064.com/n/147739.html