您的位置:首页 > 其它

cas-server-3.5.2 SSO 单点登入 带验证码 登入后可携带自定义用户信息(二)

2017-09-04 10:10 417 查看
本次我们接着上次内容继续讲解,在增加验证码之后,增加携带用户信息的功能。

终极版sso本下载地址:http://download.csdn.net/download/jieyuanyihao/9963514

携带用户信息的客户端下载地址:http://download.csdn.net/download/jieyuanyihao/9963500

cas-client-3.2.1-release.zip下载地址:http://download.csdn.net/download/jieyuanyihao/9959828

cas-server-3.5.2-release.zip 下载地址:http://download.csdn.net/download/jieyuanyihao/9959821



下面我们开始第二章的讲解。

1、首先我们在 /sso/src/main/webapp/WEB-INF/deployerConfigContext.xml文件中找到

<bean id="attributeRepository"
class="org.jasig.services.persondir.support.StubPersonAttributeDao">
,把整个bean注释掉,改成下面这样
<bean  class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao" id="attributeRepository">
<constructor-arg index="0" ref="dataSource"/>
<constructor-arg index="1" value="select user_id,user_name,org_code from sys_user where {0}"/>
<property name="queryAttributeMapping">
<map>
<entry key="username" value="user_name"/>
</map>
</property>
<property name="resultAttributeMapping">
<map>
<entry key="user_id" value="userId"/>
<entry key="user_name" value="userName"/>
<entry key="org_code" value="orgCode"/>
</map>
</property>
</bean>



2、还是在 /sso/src/main/webapp/WEB-INF/deployerConfigContext.xml文件中找到

<bean
id="serviceRegistryDao"
class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
在里面添加
<property name="ignoreAttributes" value="true"/&
b531
gt;
<property name="allowedAttributes">
<list>
<value>userId</value>
<value>userName</value>
<value>orgCode</value>
</list>
</property>



3、在表sys_user里面添加user_id和org_code两个字段。

4、/sso/src/main/webapp/WEB-INF/view/jsp/protocol/2.0/casServiceValidationSuccess.jsp这个页面在server验证成功后,负责生成与客户端交互的xml信息,在默认的casServiceValidationSuccess.jsp中,只包括用户名,并不提供其他的属性信息,因此需要对页面进行扩展。

<c:if
test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes) > 0}">
<cas:attributes>
<c:forEach var="attr"
items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}">
<cas:${attr.key}>${attr.value}</cas:${attr.key}>
</c:forEach>
</cas:attributes>
</c:if>



5、修改客户端

ssoClient1和ssoClient2的web.xml都添加

<filter>
<filter-name>SampleSSOSessionFilter</filter-name>
<filter-class>org.sky.framework.session.SampleSSOSessionFilter</filter-class>
<init-param>
<param-name>exclude</param-name>
<param-value>/syserror.jsp
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SampleSSOSessionFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>



修改ssoClient1的index.jsp代码为

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.bean.UserInfo" %>
<%
UserInfo us=(UserInfo)session.getAttribute("USER_SESSION_OBJECT");
String uname=us.getUserName();
String orgCode = us.getOrgCode();
long userId = us.getUserId();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ssoClient1</title>
</head>
<body>
<h1>this is sso client1</h1>
<h1>Hello: <%=uname%> , orgCode = <%=orgCode %> , userId = <%=userId %> </h1>
<a href="http://localhost:8080/ssoClient2/index.jsp">go to sso client2</a>
<a href="http://localhost:8080/sso/logout">退出</a>
</body>
</html>


修改ssoClient2的index.jsp代码为
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.bean.UserInfo" %>
<%
UserInfo us=(UserInfo)session.getAttribute("USER_SESSION_OBJECT");
String uname=us.getUserName();
String orgCode = us.getOrgCode();
long userId = us.getUserId();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ssoClient2</title>
</head>
<body>
<h1>this is sso client2</h1>
<h1>Hello: <%=uname%> , orgCode = <%=orgCode %> , userId = <%=userId %> </h1>
<a href="http://localhost:8080/ssoClient1/index.jsp">go to sso client1</a>
<a href="http://localhost:8080/sso/logout">退出</a>
</body>
</html>
ssoClient1和ssoClient2都添加类UserInfo和SampleSSOSessionFilter

package com.bean;

public class UserInfo {

private long id;

private long userId;

private String userName;

private String englishName;

private String shortName;

private String cnName;

private String tel;

private String email;

private String qq;

private String sex;

private double height;

private double weight;

private String address;

private String remark;

private String orgCode;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public long getUserId() {
return userId;
}

public void setUserId(long userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getEnglishName() {
return englishName;
}

public void setEnglishName(String englishName) {
this.englishName = englishName;
}

public String getShortName() {
return shortName;
}

public void setShortName(String shortName) {
this.shortName = shortName;
}

public String getCnName() {
return cnName;
}

public void setCnName(String cnName) {
this.cnName = cnName;
}

public String getTel() {
return tel;
}

public void setTel(String tel) {
this.tel = tel;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getQq() {
return qq;
}

public void setQq(String qq) {
this.qq = qq;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public double getHeight() {
return height;
}

public void setHeight(double height) {
this.height = height;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getRemark() {
return remark;
}

public void setRemark(String remark) {
this.remark = remark;
}

public String getOrgCode() {
return orgCode;
}

public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}

}

package org.sky.framework.session;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bean.UserInfo;

public class SampleSSOSessionFilter implements Filter {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
private String excluded;
private static final String EXCLUDE = "exclude";
private boolean no_init = true;
private ServletContext context = null;
private FilterConfig config;
String url = "";
String actionName = "";

public void setFilterConfig(FilterConfig paramFilterConfig) {
if (this.no_init) {
this.no_init = false;
this.config = paramFilterConfig;
if ((this.excluded = paramFilterConfig.getInitParameter("exclude")) != null)
this.excluded += ",";
}
}

private String getActionName(String actionPath) {
logger.debug("filter actionPath====" + actionPath);
StringBuffer actionName = new StringBuffer();
try {
int begin = actionPath.lastIndexOf("/");
if (begin >= 0) {
actionName.append(actionPath.substring(begin, actionPath.length()));
}
} catch (Exception e) {
}
return actionName.toString();
}

private boolean excluded(String paramString) {
// logger.info("paramString====" + paramString);
// logger.info("excluded====" + this.excluded);
// logger.info(this.excluded.indexOf(paramString + ","));
if ((paramString == null) || (this.excluded == null))
return false;
return (this.excluded.indexOf(paramString + ",") >= 0);
}

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
UserInfo uinfo = new UserInfo();
HttpSession se = req.getSession();

url = req.getRequestURI();
actionName = getActionName(url);
//actionName = url;
logger.debug(">>>>>>>>>>>>>>>>>>>>SampleSSOSessionFilter: request actionname" + actionName);
if (!excluded(actionName)) {
try {
uinfo = (UserInfo) se.getAttribute("USER_SESSION_OBJECT");
AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();
String userName = principal.getName();
logger.info("userName: " + userName);
if (userName != null && userName.length() > 0 && uinfo == null) {
Map attributes = principal.getAttributes();
String orgCode = (String) attributes.get("orgCode");
Object userId = attributes.get("userId");
long userIdl = 0;
if(userId == null || userId.toString().length() < 1) {
userIdl = 0;
} else {
userIdl = Long.parseLong(attributes.get("userId").toString());
}
uinfo = new UserInfo();
String[] userAttri = userName.split(",");
uinfo.setUserName(userAttri[0]);
uinfo.setOrgCode(orgCode);
uinfo.setUserId(userIdl);
se.setAttribute("USER_SESSION_OBJECT", uinfo);
}
} catch (Exception e) {
logger.error("SampleSSOSessionFilter error:" + e.getMessage(), e);
resp.sendRedirect(req.getContextPath() + "/syserror.jsp");
return;
}
} else {
arg2.doFilter(request, response);
return;
}
try {
arg2.doFilter(request, response);
return;
} catch (Exception e) {
logger.error("SampleSSOSessionFilter fault: " + e.getMessage(), e);
}
}

@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config = config;
if ((this.excluded = config.getInitParameter("exclude")) != null)
this.excluded += ",";
this.no_init = false;
}
}


这样登入后就可以看到你想要的用户信息了





到此整个sso单点登入到此结束,希望这些对大家的学习有帮助。

声明,本文部分内容转载自:http://blog.csdn.net/carl_china/article/details/48845597
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: