自定义shiro
- 创建CustomRealm
public class CustomRealm extends AuthorizingRealm {
Map<String,String> userMap = new HashMap<>(16);
{
userMap.put("Tom","123");
super.setName("customRealm");
}
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName = (String) principalCollection.getPrimaryPrincipal();
Set<String> roles = getRolesByUserName(userName);
Set<String>permissions = getPermissionsByUserName(userName);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setStringPermissions(permissions);
simpleAuthorizationInfo.setRoles(roles);
return simpleAuthorizationInfo;
}
private Set<String> getPermissionsByUserName(String userName) {
Set<String> set = new HashSet<>();
set.add("user:delete");
set.add("user:add");
return set;
}
private Set<String>getRolesByUserName(String userName){
Set<String> set = new HashSet<>();
set.add("admin");
set.add("user");
return set;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.从主体传过来的认证信息中,获得用户名
String userName = (String) authenticationToken.getPrincipal();
//2.通过用户名到数据中获取凭证
String password = getPasswordByUserName(userName);
if (password == null){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo
("Tom",password,"customRealm");
return authenticationInfo;
}
//模拟数据库
private String getPasswordByUserName(String userName) {
return userMap.get(userName);
}
}
2.测试类
public class CustomRealmTest {
CustomRealm customRealm = new CustomRealm();
@Test
public void testAuthenication(){
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(customRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("Tom","123");
subject.login(token);
System.out.println(subject.isAuthenticated());
subject.checkRole("admin");
subject.checkPermissions("user:add","user:delete");
}
}