1 Star 0 Fork 0

平凡之路Free / shiro

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
AdminRealm.java 2.87 KB
一键复制 编辑 原始数据 按行查看 历史
平凡之路Free 提交于 2017-04-18 19:14 . shiro框架 多角色登陆:
package com.yd.sinjutech.shiro;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.yd.sinjutech.entity.AgentLogin;
import com.yd.sinjutech.entity.Login;
import com.yd.sinjutech.service.LoginService;
public class AdminRealm extends AuthorizingRealm {
@Autowired
private LoginService loginService;
private AgentLogin dbAgentLogin = new AgentLogin();
/**
* 授权逻辑
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = (String) principals.getPrimaryPrincipal();// 获取用户名
/**
* 根据用户名从数据库查询出权限 在设置进角色的集合和权限的集合
*/
// 角色的集合
Set<String> roles = new HashSet<String>();
roles.add(userName);
// 权限的集合
Set<String> permissions = new HashSet<String>();
/**
* 权限 角色添加进权限验证
*/
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();// 授权
authorizationInfo.addStringPermissions(permissions);// 设置权限
return authorizationInfo;
}
/**
* 登录逻辑
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
/**
* 自定义登录实现
*/
CustomizedToken customizedToken = (CustomizedToken) token;
String userName = (String) customizedToken.getPrincipal();// 根据userName查询登录数据库
// securityManager:安全管理器
SecurityManager securityManager= new DefaultSecurityManager();
// SecurityUtils:全局的安全工具
SecurityUtils.setSecurityManager(securityManager);
Login login = new Login();
AgentLogin agentLogin = new AgentLogin();
login.setLogin(userName);
agentLogin.setLogin(userName);
/**
* 登录获取用户数据
*/
dbAgentLogin = loginService.agentLogin(agentLogin);
/**
* 判断账号是否存在
*/
if ( dbAgentLogin == null) {
throw new UnknownAccountException();
}
/**
* 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现
*/
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, dbAgentLogin.getPassword(), getName());// 用户名和密码//验证
return info;
}
}
Java
1
https://gitee.com/shince/afsdf.git
git@gitee.com:shince/afsdf.git
shince
afsdf
shiro
master

搜索帮助