<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName" default-lazy-init="true"> <jaxws:endpoint id="webServiceSample" address="/WebServiceSample" implementor="cn.org.coral.biz.examples.webservice.WebServiceSampleImpl"> <jaxws:inInterceptors> <bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" /> <bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor"> <constructor-arg> <map> <entry key="action" value="UsernameToken" /> <entry key="passwordType" value="PasswordText" /> <entry key="passwordCallbackClass" value="cn.org.coral.biz.examples.webservice.handler.WsAuthHandler" /> </map> </constructor-arg> </bean> </jaxws:inInterceptors> </jaxws:endpoint> </beans>
package cn.org.coral.biz.examples.webservice.handler; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class WsAuthHandler implements CallbackHandler{ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; if (pc.getIdentifer().equals("ws-client")){ if (!pc.getPassword().equals("admin")) { throw new SecurityException("wrong password"); } }else{ throw new SecurityException("wrong username"); } } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName" default-lazy-init="true"> <!-- ws clinet --> <bean id="webServiceSampleClient" class="cn.org.coral.biz.examples.webservice.WebServiceSample" factory-bean="webServiceSampleClientFactory" factory-method="create" /> <bean id="webServiceSampleClientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean"> <property name="serviceClass" value="cn.org.coral.biz.examples.webservice.WebServiceSample" /> <property name="address" value="http://88.148.29.54:8080/aio/services/WebServiceSample" /> <property name="outInterceptors"> <list> <bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" /> <ref bean="wss4jOutConfiguration" /> </list> </property> </bean> <bean id="wss4jOutConfiguration" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor"> <property name="properties"> <map> <entry key="action" value="UsernameToken" /> <entry key="user" value="ws-client" /> <entry key="passwordType" value="PasswordText" /> <entry> <key> <value>passwordCallbackRef</value> </key> <ref bean="passwordCallback" /> </entry> </map> </property> </bean> <bean id="passwordCallback" class="cn.org.coral.biz.examples.webservice.handler.WsClinetAuthHandler"> </bean> </beans>
package cn.org.coral.biz.examples.webservice.handler; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class WsClinetAuthHandler implements CallbackHandler{ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; int usage = pc.getUsage(); System.out.println("identifier: " + pc.getIdentifer()); System.out.println("usage: " + pc.getUsage()); if (usage == WSPasswordCallback.USERNAME_TOKEN) { // username token pwd... pc.setPassword("admin"); } else if (usage == WSPasswordCallback.SIGNATURE) { // set the password for client's keystore.keyPassword pc.setPassword("keyPassword"); } } } }
package cn.org.coral.biz.examples.webservice; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; import org.springframework.util.Assert; public class TestWebService extends AbstractDependencyInjectionSpringContextTests { WebServiceSample webServiceSampleClient; @Override protected String[] getConfigLocations() { setAutowireMode(AUTOWIRE_BY_NAME); return new String[] { "classpath:/cn/org/coral/biz/examples/webservice/wsclient-context.xml" }; } /** * @param webServiceSampleClient the webServiceSampleClient to set */ public void setWebServiceSampleClient(WebServiceSample webServiceSampleClient) { this.webServiceSampleClient = webServiceSampleClient; } public void testSay(){ String result = webServiceSampleClient.say(" world"); Assert.hasText(result); } }
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Windows.Forms;
using WindowsApplication1.WebReference;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
WindowsApplication1.WebReference.WebServiceSampleImplService service = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String str = "";
try
{
str = service.say("Libin");
}
catch (Exception we)
{
str = we.Message;
}
//MessageBox.Show(str);
textBox1.Text = str ;
}
private void Form1_Load(object sender, EventArgs e)
{
service = new WebServiceSampleImplService();
label1.Text = "WS.url:" + service.Url + "\r\n";
}
private void button2_Click(object sender, EventArgs e)
{
String str = "";
try
{
User user = new User();
user.id = 1;
user.name = "Libin";
str = "userName:" + service.sayUserName(user);
}
catch (Exception we)
{
str = we.Message;
}
//MessageBox.Show(str);
textBox1.Text = str;
}
private void button3_Click(object sender, EventArgs e)
{
String str = "";
try
{
Object[] users = service.findUsers();
for (int i = 0; i < users.Length; i++)
{
User user = (User)users[i];
str += "id:"+user.id + " name:" + user.name + "\r\n";
}
}
catch (Exception we)
{
str = we.Message;
}
//MessageBox.Show(str);
textBox1.Text = str;
}
}
}
<import resource="classpath*:META-INF/cxf/cxf.xml" />
<import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath*:META-INF/cxf/cxf-servlet.xml" />
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
/**
* WebService鎺ュ彛瀹氫箟綾?
*
* 浣跨敤@WebService灝嗘帴鍙d腑鐨勬墍鏈夋柟娉曡緭鍑轟負Web Service.
* 鍙敤annotation瀵硅緗柟娉曘佸弬鏁板拰榪斿洖鍊煎湪WSDL涓殑瀹氫箟.
*/
@WebService
public interface WebServiceSample {
/**
* 涓涓畝鍗曠殑鏂規硶,榪斿洖涓涓瓧絎︿覆
* @param hello
* @return
*/
String say(String hello);
/**
* 紼嶅井澶嶆潅涓浜涚殑鏂規硶,浼犻掍竴涓璞$粰鏈嶅姟绔鐞?br /> * @param user
* @return
*/
String sayUserName(
@WebParam(name = "user")
UserDTO user);
/**
* 鏈澶嶆潅鐨勬柟娉?榪斿洖涓涓狶ist灝佽鐨勫璞¢泦鍚?br /> * @return
*/
public
@WebResult(partName="o")
ListObject findUsers();
}
/**
* WebService瀹炵幇綾?
*
* 浣跨敤@WebService鎸囧悜Interface瀹氫箟綾誨嵆鍙?
*/
@WebService(endpointInterface = "cn.org.coral.biz.examples.webservice.WebServiceSample")
public class WebServiceSampleImpl implements WebServiceSample {
public String sayUserName(UserDTO user) {
return "hello "+user.getName();
}
public String say(String hello) {
return "hello "+hello;
}
public ListObject findUsers() {
ArrayList<Object> list = new ArrayList<Object>();
list.add(instancUser(1,"lib"));
list.add(instancUser(2,"mld"));
list.add(instancUser(3,"lq"));
list.add(instancUser(4,"gj"));
ListObject o = new ListObject();
o.setList(list);
return o;
}
private UserDTO instancUser(Integer id,String name){
UserDTO user = new UserDTO();
user.setId(id);
user.setName(name);
return user;
}
}
/**
* Web Service浼犺緭User淇℃伅鐨凞TO.
*
* 鍒嗙entity綾諱笌web service鎺ュ彛闂寸殑鑰﹀悎錛岄殧緇漞ntity綾葷殑淇敼瀵規帴鍙g殑褰卞搷.
* 浣跨敤JAXB 2.0鐨刟nnotation鏍囨敞JAVA-XML鏄犲皠錛屽敖閲忎嬌鐢ㄩ粯璁ょ害瀹?
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "User")
public class UserDTO {
protected Integer id;
protected String name;
public Integer getId() {
return id;
}
public void setId(Integer value) {
id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
name = value;
}
}
/**
* <p>Java class for listObject complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="listObject">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="list" type="{http://www.w3.org/2001/XMLSchema}anyType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listObject", propOrder = { "list" })
public class ListObject {
@XmlElement(nillable = true)
protected List<Object> list;
/**
* Gets the value of the list property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the list property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getList() {
if (list == null) {
list = new ArrayList<Object>();
}
return this.list;
}
public void setList(ArrayList<Object> list) {
this.list = list;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName" default-lazy-init="true">
<jaxws:endpoint id="webServiceSample"
address="/WebServiceSample" implementor="cn.org.coral.biz.examples.webservice.WebServiceSampleImpl"/>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName" default-lazy-init="true">
<!-- ws client -->
<bean id="identityValidateServiceClient" class="cn.org.coral.admin.service.IdentityValidateService"
factory-bean="identityValidateServiceClientFactory" factory-method="create" />
<bean id="identityValidateServiceClientFactory"
class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
<property name="serviceClass"
value="cn.org.coral.admin.service.IdentityValidateService" />
<property name="address"
value="http://88.148.29.54:8080/coral/services/IdentityValidateService"/>
</bean>
</beans>
package test.coral.sample;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import cn.org.coral.biz.examples.webservice.WebServiceSample;
import cn.org.coral.biz.examples.webservice.dto.UserDTO;
public class TestWebServiceSample extends
AbstractDependencyInjectionSpringContextTests {
WebServiceSample webServiceSampleClient;
public void setWebServiceSampleClient(WebServiceSample webServiceSampleClient) {
this.webServiceSampleClient = webServiceSampleClient;
}
@Override
protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_NAME);
//spring 瀹㈡埛绔厤緗枃浠朵繚瀛樹綅緗?br /> return new String[] { "classpath:/cn/org/coral/biz/examples/webservice/wsclient-context.xml" };
}
public void testWSClinet(){
Assert.hasText(webServiceSampleClient.say(" world"));
}
}
<authentication mode="Forms" >
<forms name="casauth" loginUrl="login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
//CAS 韜喚楠岃瘉 鏈嶅姟鍣ㄥ湴鍧
private const string CASHOST = "https://sso.gzps.net:8443/cas/";
protected void Page_Load(object sender, EventArgs e)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Look for the "ticket=" after the "?" in the URL
string tkt = Request.QueryString["ticket"];
// This page is the CAS service=, but discard any query string residue
string service = Request.Url.GetLeftPart(UriPartial.Path);
// First time through there is no ticket=, so redirect to CAS login
if (tkt == null || tkt.Length == 0)
{
string redir = CASHOST + "login?" +
"service=" + service;
Response.Redirect(redir);
return;
}
// Second time (back from CAS) there is a ticket= to validate
string validateurl = CASHOST + "serviceValidate?" +
"ticket=" + tkt + "&"+
"service=" + service;
StreamReader Reader = new StreamReader( new WebClient().OpenRead(validateurl));
string resp = Reader.ReadToEnd();
// I like to have the text in memory for debugging rather than parsing the stream
// Some boilerplate to set up the parse.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
string netid = null;
// A very dumb use of XML. Just scan for the "user". If it isn't there, its an error.
while (reader.Read())
{
if (reader.IsStartElement()) {
string tag = reader.LocalName;
if (tag=="user")
netid = reader.ReadString();
}
}
// if you want to parse the proxy chain, just add the logic above
reader.Close();
// If there was a problem, leave the message on the screen. Otherwise, return to original page.
if (netid == null)
{
Label1.Text = "CAS returned to this application, but then refused to validate your identity.";
}
else
{
Session["UserName"] = netid;
Label1.Text = "Welcome " + netid;
FormsAuthentication.RedirectFromLoginPage(netid, false); // set netid in ASP.NET blocks
}
}
}
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class MyPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint
, X509Certificate certificate
, WebRequest request
, int certificateProblem) {
//Return True to force the certificate to be accepted.
return true;
} // end CheckValidationResult
} // class MyPolicy
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
<!-- ========= Acegi as a CAS Client鐨勯厤緗?============ --> <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.cas.CasProcessingFilter"> <property name="authenticationManager" ref="authenticationManager" /> <property name="authenticationFailureUrl" value="/login.do?login_error=1" /> <property name="defaultTargetUrl" value="/main.do" /> <property name="filterProcessesUrl"> <value>/j_acegi_cas_security_check</value> </property> <property name="rememberMeServices" ref="rememberMeServices" /> <property name="exceptionMappings"> <value> org.acegisecurity.AuthenticationServiceException=/login.do?login_error=user_not_found_error org.acegisecurity.BadCredentialsException=/login.do?login_error=user_psw_error org.acegisecurity.concurrent.ConcurrentLoginException=/login.do?login_error=too_many_user_error org.acegisecurity.DisabledException=/login.do?login_error=disabled_user_error </value> </property> </bean> <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter"> <property name="authenticationEntryPoint"> <ref local="casProcessingFilterEntryPoint"/> </property> <property name="accessDeniedHandler"> <bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl"> <property name="errorPage" value="/errors/accessDenied.jsp" /> </bean> </property> </bean> <!-- cas config --> <bean id="casProcessingFilterEntryPoint" class="org.acegisecurity.ui.cas.CasProcessingFilterEntryPoint"> <property name="loginUrl"><value>https://sso.gzps.net:8443/cas/login</value></property> <property name="serviceProperties"><ref local="serviceProperties"/></property> </bean> <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager"> <property name="providers"> <list> <ref local="casAuthenticationProvider"/> </list> </property> </bean> <bean id="casAuthenticationProvider" class="org.acegisecurity.providers.cas.CasAuthenticationProvider"> <property name="casAuthoritiesPopulator"><ref bean="casAuthoritiesPopulator"/></property> <property name="casProxyDecider"><ref local="casProxyDecider"/></property> <property name="ticketValidator"><ref local="casProxyTicketValidator"/></property> <property name="statelessTicketCache"><ref local="statelessTicketCache"/></property> <property name="key"><value>my_password_for_this_auth_provider_only</value></property> </bean> <bean id="casProxyTicketValidator" class="org.acegisecurity.providers.cas.ticketvalidator.CasProxyTicketValidator"> <property name="casValidate"><value>https://sso.gzps.net:8443/cas/proxyValidate</value></property> <property name="serviceProperties"><ref local="serviceProperties"/></property> </bean> <!-- <bean id="casProxyDecider" class="org.acegisecurity.providers.cas.proxy.AcceptAnyCasProxy" /> --> <bean id="casProxyDecider" class="org.acegisecurity.providers.cas.proxy.RejectProxyTickets" /> <bean id="serviceProperties" class="org.acegisecurity.ui.cas.ServiceProperties"> <property name="service"> <value>http://localhost:8080/aio/j_acegi_cas_security_check</value> </property> <property name="sendRenew"> <value>false</value> </property> </bean> <bean id="statelessTicketCache" class="org.acegisecurity.providers.cas.cache.EhCacheBasedTicketCache"> <property name="cache"> <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> </property> <property name="cacheName" value="userCache"/> </bean> </property> </bean> <bean id="casAuthoritiesPopulator" class="org.acegisecurity.providers.cas.populator.DaoCasAuthoritiesPopulator">
<property name="userDetailsService"><ref local="userDetailsService"/></property>
</bean>
<bean id="casProcessingFilter" class="org.acegisecurity.ui.cas.CasProcessingFilter">
<property name="authenticationManager"><ref local="authenticationManager"/></property>
<property name="authenticationFailureUrl"><value>/casfailed.jsp</value></property>
<property name="defaultTargetUrl"><value>/</value></property>
<property name="filterProcessesUrl"><value>/j_acegi_cas_security_check</value></property>
</bean>
<!-- ======================================================= -->
<!-- 鏁版嵁婧愬畾涔?-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<!--
passwordEncoder銆浣跨敤Md5綆楁硶鍔犲瘑
-->
<bean id="passwordEncoder"
class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder" autowire="byName">
<constructor-arg value="MD5"/>
</bean>
<!--
<bean
class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />
-->
<bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
<property name="sql" value="select password from CORE_USERS where logid=?" />
<property name="passwordEncoder" ref="passwordEncoder"/>
<property name="dataSource" ref="dataSource" />
</bean>
db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc\:oracle\:thin\:@192.168.1.1\:1521\:xxxx
db.username=xxxx
db.password=xxxx
<Connector protocol="org.apache.coyote.http11.Http11Protocol"
port="8443" minSpareThreads="5" maxSpareThreads="75"
enableLookups="true" disableUploadTimeout="true"
acceptCount="100" maxThreads="200"
scheme="https" secure="true" SSLEnabled="true"
keystoreFile="C:/Documents and Settings/Administrator/.keystore" keystorePass="changeit"
truststoreFile="D:/Java/jdk1.6.0_02/jre/lib/security/cacerts"
clientAuth="false" sslProtocol="TLS"/>
<!-- CAS -->
<filter>
<filter-name>CAS Filter</filter-name>
<filter-class>edu.yale.its.tp.cas.client.filter.CASFilter</filter-class>
<init-param>
<param-name>edu.yale.its.tp.cas.client.filter.loginUrl</param-name>
<param-value>https://sso.gzps.net:8443/cas/login</param-value>
</init-param>
<init-param>
<param-name>edu.yale.its.tp.cas.client.filter.validateUrl</param-name>
<param-value>https://sso.gzps.net:8443/cas/serviceValidate</param-value>
</init-param>
<init-param>
<param-name>edu.yale.its.tp.cas.client.filter.serverName</param-name>
<param-value>88.148.29.54:8080</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CAS Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>