1、创建SecurityManager
2、主体授权
3、SecurityManager授权
4、Authorizer授权
5、Realm获取角色权限数据
package com.zjc.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;
public class AuthenticationTest {
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@Before
public void addUser(){
simpleAccountRealm.addAccount("jiangcheng","123456","admin","user");
}
@Test
public void testAuthentication(){
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);
//主体提交认证系统
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
//若账户输入出错 会出现 未知账户异常
//org.apache.shiro.authc.UnknownAccountException:
// Realm [org.apache.shiro.realm.SimpleAccountRealm@7a92922]
// was unable to find account data for the submitted AuthenticationToken
// [org.apache.shiro.authc.UsernamePasswordToken - jiangcheng1, rememberMe=false].
//若密码输入出错 会出现 不正确的凭证异常
// org.apache.shiro.authc.IncorrectCredentialsException:
// Submitted credentials for token
// [org.apache.shiro.authc.UsernamePasswordToken - jiangcheng, rememberMe=false]
// did not match the expected credentials.
UsernamePasswordToken token = new UsernamePasswordToken("jiangcheng","123456");
//登陆
subject.login(token);
//验证是否成功
System.out.println("isAuthenticated:"+subject.isAuthenticated());
//验证用户是否有这样的角色
//如果没有这样的角色会出现异常
//org.apache.shiro.authz.UnauthorizedException: Subject does not have role [admin1]
subject.checkRoles("admin","user");
//登出
subject.logout();
System.out.println("isAuthenticated:"+subject.isAuthenticated());
}
}
网友评论