二、Shiro 认证开发

时间:2024-08-30 12:06:26

I、java开发

环境准备

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>

shiro配置文件: shiro.ini

[users]
zhang3=123123
li4=123456

测试

//测试认证
public class TestAuthor {
/**
* 认证
* 安全管理器
* 获取主题
* token
*
*/
public static void main(String[] args) {
//通过安全管理器工厂
IniSecurityManagerFactory iniSecurityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");
//获得安全管理器工厂
SecurityManager securityManager = iniSecurityManagerFactory.getInstance();
//将安全管理器交给安全工具类
SecurityUtils.setSecurityManager(securityManager); //主体对象
Subject subject = SecurityUtils.getSubject();
//构建token
UsernamePasswordToken token = new UsernamePasswordToken("zhang3", "123123");
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
}
//验证是否通过
System.out.println(subject.isAuthenticated());
} }

异常

IncorrectCredentialsException:密码输入错误

UnknownAccountException:账户对比失败

DisabledAccountException:帐号被禁用

LockedAccountException:帐号被锁定

ExcessiveAttemptsException:登录失败次数过多

ExpiredCredentialsException:凭证过期

底层认证思路

二、Shiro 认证开发

public class MyRealm extends AuthenticatingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
/**
* 假装查询数据库
*
*
*/
//获取用户名
String principal = (String) authenticationToken.getPrincipal();
if (principal.equals("zhang3")){
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("zhang3", "123123", this.getName());
return simpleAuthenticationInfo; }
return null;
} }