shiro中通过返回更多用户信息
在重写的AuthorizingRealm中方法doGetAuthenticationInfo中传入封装的用户实体即可。
UserDetails userDetails=null;
try {
userDetails = this.userDetailsService.loadUserByUsername(token1.getUsername());
} catch (UsernameNotFoundException notFound) {
return null;
}
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(userDetails, userDetails.getPassword(),getName());
示例:
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.common.shrio; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import com.hanker.config.ConfigInfo; import com.opensymphony.xwork2.ActionContext; import core.apps.rbac.login.UserDetailsBean; import core.session.filter.RemoteSessionRequest; import core.session.manager.WebSession; import core.session.manager.WebSessionManager; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.apache.commons.lang.StringUtils; 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.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ByteSource; import org.apache.shiro.web.subject.WebSubject; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import core.apps.rbac.entity.RoleSkillBTEntity; import core.apps.rbac.manage.service.UserService; import core.apps.rbac.vo.SelectRoleVO; import core.db.dao.IBaseService; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 几个概念�? 翻译不好,从官方上找来的原�?. 如果不懂�? 使用 “有道词典�?��?�来源于�? http://shiro.apache.org/java-authentication-guide.html * * Subject Security specific user 'view' of an application user. It can be a human being, a third-party process, * a server connecting to you application application, or even a cron job. Basically, it is anything or * anyone communicating with your application. * * Principals A subjects identifying attributes. First name, last name, social security number, username * * Credentials secret data that are used to verify identities. Passwords, Biometric data, x509 certificates, * * Realms Security specific DAO, data access object, software component that talkts to a backend data source. * If you have usernames and password in LDAP, then you would have an LDAP Realm that would communicate * with LDAP. The idea is that you would use a realm per back-end data source and Shiro would know how * to coordinate with these realms together to do what you have to do. * * @author fq1798 * */ public class ShiroDbRealm extends AuthorizingRealm { @Autowired private UserDetailsService userDetailsService; @Autowired(required = false) private UserService userService ; @Autowired(required = false) private IBaseService baseService ; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //得到 doGetAuthenticationInfo 方法中传入的凭证 UserDetails shiroUser = (UserDetails) principals.fromRealm(getName()).iterator().next(); List<String> roleList = new ArrayList<String>(); List<String> permissionList = new ArrayList<String>(); String userName = shiroUser.getUsername(); // if(StringUtils.equals("20160606", userName)) { List<SelectRoleVO> selectedRoleList = new ArrayList(); if(null!=shiroUser){ selectedRoleList = this.userService.findUserRoleListbyUserId(shiroUser.getUsername(), true); if (null != selectedRoleList && selectedRoleList.size() > 0) { for(SelectRoleVO r: selectedRoleList){ roleList.add(r.getRoleId()); // List<RoleSkillBTEntity> roleSkillBTEntity = baseService.findObjects(RoleSkillBTEntity.class, "roleId", r.getRoleId()); String sql = "SELECT b.*,s.URL from s_rbac_roleskillb b ,s_rbac_skill s WHERE b.SKILLID=s.SKILLID AND b.ROLEID='"+r.getRoleId()+"'"; List<Map> branchArr = this.baseService.queryForJDBCList(sql); if (null != branchArr&& branchArr.size() > 0) { for (Iterator<Map> it = branchArr.iterator(); it.hasNext();) {//遍历角色菜单 Map resource = it.next(); if (!"".equals(resource)&&resource!=null) { permissionList.add(resource.get("URL")+""); } } } } } } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //这个确定页面�?<shiro:hasRole>标签的name的�?? // roleList.add("admin"); info.addRoles(roleList); //这个就是页面�? <shiro:hasPermission> 标签的name的�?? // permissionList.add("/flex/rbac/getSkillMenuAndSkillsForShow.action"); // permissionList.add("/flex/uifrm/index.jsp"); info.addStringPermissions(permissionList); return info; } /** * AuthenticationInfo represents a Subject's (aka user's) stored account information * relevant to the authentication/log-in process only. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // UsernamePasswordToken usernamePasswordToke = (UsernamePasswordToken)token; // // // String username = usernamePasswordToke.getUsername(); // // // System.out.println("====================doGetAuthenticationInfo begin =========================="); // System.out.println("username: " + username); // System.out.print("password: "); // System.out.println(usernamePasswordToke.getPassword()); // System.out.println("principal: " + usernamePasswordToke.getPrincipal()); // System.out.println("======================doGetAuthenticationInfo end ========================"); // // // /** // * Constructor that takes in a single 'primary' principal of the account, its corresponding hashed credentials, the salt used to hash the credentials, and the name of the realm to associate with the principals. // * This is a convenience constructor and will construct a PrincipalCollection based on the principal and realmName argument. // * // * // * Parameters: // * // * principal - the 'primary' principal associated with the specified realm. // * hashedCredentials - the hashed credentials that verify the given principal. // * credentialsSalt - the salt used when hashing the given hashedCredentials // * realmName - the realm from where the principal and credentials were acquired. // */ // if(StringUtils.equals("admin", username)) { // return new SimpleAuthenticationInfo(new ShiroUser("admin", "admin"), "admin", ByteSource.Util.bytes("admin"), getName()); // } else if(StringUtils.equals("test", username)) { // return new SimpleAuthenticationInfo(new ShiroUser("test", "test"), "test", ByteSource.Util.bytes("test"), getName()); // } // return null; // 获取基于用户名和密码的令牌 UsernamePasswordToken token1 = (UsernamePasswordToken) token; UserDetails userDetails=null; try { userDetails = this.userDetailsService.loadUserByUsername(token1.getUsername()); } catch (UsernameNotFoundException notFound) { return null; } try { if (null != userDetails) { AuthenticationInfo authcInfo = new SimpleAuthenticationInfo( userDetails, userDetails.getPassword(), getName()); this.setSession("currentUser", userDetails); this.setSession("ACEGI_SECURITY_LAST_USERNAME", userDetails.getUsername()); String weixinOrderDetailUrl = ConfigInfo.getPropertiesValue("weixinOrderDetailUrl"); this.setSession("weixinOrderDetailUrl", weixinOrderDetailUrl); //分机号 this.setSession("EXTNO", ""); return authcInfo; } } catch (Exception e) { e.printStackTrace(); } return null;// null时会在LoginController中抛出UnknownAccountException异常 } private void setSession(Object key, Object value) throws Exception{ Subject currentUser = SecurityUtils.getSubject(); // WebSessionManager webSession = new WebSessionManager(); // webSession.createSession() // ActionContext ctx = ActionContext.getContext(); HttpServletRequest request1 =(HttpServletRequest) ((WebSubject)SecurityUtils.getSubject()).getServletRequest(); //ServletActionContext.getRequest(); HttpServletResponse response1 =(HttpServletResponse) ((WebSubject)SecurityUtils.getSubject()).getServletResponse(); //ServletActionContext.getRequest(); // HttpServletRequest request2 =(HttpServletRequest) request1; // HttpServletRequest request = ServletActionContext.getRequest(); // Map request3 = (Map)ActionContext.getContext().get("request"); Cookie[] cookies = request1.getCookies(); UserDetailsBean agentUser =(UserDetailsBean)currentUser.getPrincipal(); String username= getCookieValue(cookies, "username"); if(value instanceof UserDetails ){ UserDetailsBean shiroUser = (UserDetailsBean) value; if(username==null||!username.equals(shiroUser.getUserId())){ username=shiroUser.getUserId(); } WebSession webSession=WebSessionManager.getInstance().getSession(username); if(webSession==null){ webSession=WebSessionManager.getInstance().createSession(username); } // UserDetailsBean shiroUser = (UserDetailsBean) value; webSession.setAttribute(username, value); webSession.getAttribute(username); } // if(value instanceof UserDetails ){ // // // } Object currentUserob= currentUser; String uk="request"; String rk="response"; // ByteArrayOutputStream out = new ByteArrayOutputStream(); // ObjectOutputStream obj = new ObjectOutputStream(out); // for(int i = 0; i<10; i++) { // obj.writeObject(request1); // } // webSession.setAttribute(uk+username, out.toByteArray()); // out = new ByteArrayOutputStream(); // obj = new ObjectOutputStream(out); // for(int i = 0; i<10; i++) { // obj.writeObject(response1); // } // webSession.setAttribute(rk+username, out.toByteArray()); // webSession.getAttribute(uk); // RemoteSessionRequest request =(RemoteSessionRequest) request2; // request.getSession().setAttribute(key+"",value); // request.getSession().getAttribute(key+""); if (null != currentUser) { Session session = currentUser.getSession(); if (null != session) { session.setAttribute(key, value); } } } /** * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息. */ public static class ShiroUser implements Serializable { private static final long serialVersionUID = -1373760761780840081L; public String loginName; public String name; public ShiroUser(String loginName, String name) { this.loginName = loginName; this.name = name; } public String getName() { return name; } /** * 本函数输出将作为默认�?<shiro:principal/>输出. */ @Override public String toString() { return loginName; } // /** // * 重载equals,只计算loginName; // */ // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this, "loginName"); // } // // /** // * 重载equals,只比较loginName // */ // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj, "loginName"); // } } private static String getCookieValue(Cookie[] cookies, String cookieName) { if (cookies == null) { return null; } for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { return cookie.getValue(); } } return null; } }
相关推荐
登录成功后,CAS会返回一个Ticket,应用通过验证这个Ticket来确认用户的身份。 4. Shiro的授权:Shiro提供了基于角色的访问控制(RBAC),你可以定义角色和权限,并在Shiro配置中指定哪些URL或操作需要特定的角色...
Apache Shiro是一个强大的Java安全框架,它提供了身份验证(Authentication)、授权(Authorization)以及会话管理...如果你遇到问题,可以参考这篇文章,或者查阅Shiro的官方文档和社区资源,以获取更多帮助。
在实际开发中,"shiro-rbac-demo-master"项目可以作为一个起点,开发者可以根据需求添加更多的角色、权限和业务逻辑。例如,可以扩展用户注册功能,增加角色的动态分配,或者实现更复杂的权限策略。此外,Shiro还...
将CAS的认证结果与Shiro的授权结合,通常在CAS验证成功后,会将用户的认证信息(如用户名、票证)传递给Shiro,Shiro再通过Realm从数据源中获取用户的角色和权限信息。这样,Shiro就可以根据这些信息进行权限控制,...
5. **错误处理**:当 AJAX 请求被 Shiro 拦截器拒绝时,返回相应的错误信息,前端可以根据这些信息展示错误提示。 6. **前端响应**:前端接收到服务器响应后,根据状态码和返回信息,决定是否显示或隐藏特定功能。 ...
3. **会话管理(Session Management)**:Shiro可以管理和监控用户的会话,包括会话超时、会话固定、分布式会话等,这在多服务器部署的环境中尤为重要。 4. **Web集成**:Shiro可以轻松地与SpringMVC集成,通过...
然而,通过源码分析可以更深入地理解Shiro的内部工作原理。 Shiro使用工厂模式来获得SecurityManager的实例,并提供了一个Factory接口,通过泛型定义了getInstance()方法。这允许Shiro通过不同工厂来创建不同的...
在本项目中,Shiro主要负责用户登录验证、权限判断和会话管理。当用户登录时,Shiro会验证其凭证,然后根据用户角色和权限设置,动态生成并显示相应的菜单。 **MyBatis** MyBatis是一个优秀的持久层框架,它支持...
在IT行业中,单点登录(Single Sign-On, SSO)是一种常见的身份验证机制,它允许用户在一个系统上登录后,无需再次认证即可访问其他多个相互信任的系统。本项目是关于如何将CAS(Central Authentication Service)与...
- **Authenticator**及**AuthenticationStrategy**:Authenticator负责执行实际的用户身份验证操作,而AuthenticationStrategy则决定了如何处理多个Realm返回的认证信息。 #### 三、授权 - **授权方式**:Shiro...
Shiro的配置包括Realm的实现,用于从数据库中获取用户信息和权限。 认证流程:用户提交用户名和密码,Shiro通过Realm验证,成功后创建Subject并绑定到当前线程。授权则通过拦截器或Filter实现,检查用户是否有访问...
本项目中,当用户通过CAS验证后,服务端会生成一个JWT令牌,这个令牌包含了用户的认证信息,前端可以将此令牌包含在后续请求中,以证明用户的身份。 6. **前后端分离**: 该项目采用前后端分离架构,前端和后端...
1. **基于JWT的Token认证方式**:在这种模式下,用户登录成功后,服务器会返回一个JWT,包含了用户的身份信息以及过期时间等。客户端每次请求时将JWT放在请求头中,服务器通过验证JWT来确认用户身份。这种方式的优点...
**CAS (Central Authentication Service)** 是一个开源的身份验证框架,主要功能是提供统一的用户身份验证服务,允许用户在多个应用系统中只需要登录一次即可访问所有相互信任的应用。CAS的核心概念包括服务提供商和...
在实际项目中,你可能还需要考虑更多细节,如密码加密、验证码、多因素认证、异常处理等,以提升系统的安全性。同时,Shiro还可以与其他框架如Spring Security一起使用,提供更强大的安全防护。
在本项目中,我们选择了 Apache Shiro,因为它更易于配置和使用,更适合快速集成到现有的 Web 项目中。 2. LDAP 2.1 简介 Lightweight Directory Access Protocol(轻量级目录访问协议)是一种用于访问和管理...
接着,我们创建Shiro的Realm, Realm是Shiro与应用程序数据源交互的接口,用于获取用户身份信息和权限信息。在这个例子中,我们可以集成MyBatis来查询数据库中的用户和角色信息。在Realm中,我们需要重写`...
- 授权逻辑错误:检查 Realm 实现,确保 `doGetAuthorizationInfo()` 方法中获取权限信息的逻辑无误,以及返回的对象(通常是 `AuthorizingRealm.PrincipalCollection`)包含了正确的角色和权限信息。 在描述中...
5. 如果验证成功,Realm返回一个代表该用户的Principal集合给Shiro,Shiro将这个Principal集合绑定到Subject中。 6. Subject完成登录,此时用户被认证为已登录。 授权方面,Shiro提供了角色(Role)和权限...
3. **CAS Client**:集成在各个应用系统中,负责与CAS Server通信,验证Ticket并获取用户信息。 4. **CAS Proxy**:如果需要对第三方服务进行安全访问,CAS还支持代理模式,通过代理Ticket来完成认证。 在"shiro-...