1
0
mirror of synced 2026-08-06 02:08:01 +00:00

SEC-2194: Add Java Config samples

This commit is contained in:
Rob Winch
2013-08-01 14:14:18 -05:00
parent 36418b964d
commit 388a4dd9db
435 changed files with 71210 additions and 51 deletions
+127
View File
@@ -0,0 +1,127 @@
// CAS sample build file
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'groovy'
def excludeModules = ['spring-security-acl', 'jsr250-api', 'spring-jdbc', 'spring-tx']
def jettyVersion = '8.1.9.v20130131'
def keystore = "$rootDir/samples/certificates/server.jks"
def password = 'password'
configurations {
casServer
excludeModules.each {name ->
runtime.exclude module: name
}
runtime.exclude group: 'org.aspectj'
}
sourceSets {
test.resources.exclude 'GebConfig.groovy'
integrationTest.groovy.srcDir file('src/integration-test/groovy')
}
eclipse.classpath.plusConfigurations += configurations.integrationTestRuntime
dependencies {
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
compile project(':spring-security-core'),
project(':spring-security-cas'),
"org.jasig.cas.client:cas-client-core:3.1.12"
runtime project(':spring-security-web'),
project(':spring-security-config'),
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
"ch.qos.logback:logback-classic:$logbackVersion",
"net.sf.ehcache:ehcache:$ehcacheVersion"
integrationTestCompile project(':spring-security-cas'),
"org.seleniumhq.selenium:selenium-htmlunit-driver:$seleniumVersion",
"org.spockframework:spock-core:$spockVersion",
"org.gebish:geb-spock:$gebVersion",
'commons-httpclient:commons-httpclient:3.1',
"org.eclipse.jetty:jetty-server:$jettyVersion",
"org.eclipse.jetty:jetty-servlet:$jettyVersion",
"org.codehaus.groovy:groovy:$groovyVersion"
}
[jettyRun, jettyRunWar]*.configure {
contextPath = "/cas-sample"
def httpConnector = jettyRunWar.class.classLoader.loadClass('org.mortbay.jetty.nio.SelectChannelConnector').newInstance()
httpConnector.port = 8080
httpConnector.confidentialPort = 8443
def httpsConnector = jettyRunWar.class.classLoader.loadClass('org.mortbay.jetty.security.SslSocketConnector').newInstance()
httpsConnector.port = 8443
httpsConnector.keystore = httpsConnector.truststore = keystore
httpsConnector.keyPassword = httpsConnector.trustPassword = password
connectors = [httpConnector, httpsConnector]
doFirst() {
System.setProperty('cas.server.host', casServer().httpsHost)
System.setProperty('cas.service.host', jettyRunWar.httpsHost)
}
}
task cas (dependsOn: [jettyRunWar]) {
jettyRunWar.dependsOn(':spring-security-samples-casserver:casServer')
}
task casServer(dependsOn: ':spring-security-samples-casserver:casServer') {
}
integrationTest.dependsOn cas
integrationTest.doFirst {
def casServiceHost = jettyRunWar.httpsHost
systemProperties['cas.server.host'] = casServer().httpsHost
systemProperties['cas.service.host'] = casServiceHost
systemProperties['geb.build.baseUrl'] = 'https://'+casServiceHost+'/cas-sample/'
systemProperties['geb.build.reportsDir'] = 'build/geb-reports'
systemProperties['jar.path'] = jar.archivePath
systemProperties['javax.net.ssl.trustStore'] = keystore
systemProperties['javax.net.ssl.trustStorePassword'] = password
}
gradle.taskGraph.whenReady {graph ->
def casServer = casServer()
[casServer,jettyRunWar]*.metaClass*.getHttpsConnector {->
def sslSocketConnClass = jettyRunWar.class.classLoader.loadClass('org.mortbay.jetty.security.SslSocketConnector')
delegate.connectors.find { it in sslSocketConnClass }
}
[casServer,jettyRunWar]*.metaClass*.getHttpsHost {->
"localhost:"+delegate.httpsConnector.port
}
jettyRunWar.metaClass.getHttpConnector {->
def channelConnClass = jettyRunWar.class.classLoader.loadClass('org.mortbay.jetty.nio.SelectChannelConnector')
delegate.connectors.find { it in channelConnClass }
}
if (graph.hasTask(cas)) {
casServer.daemon = true
}
if(graph.hasTask(integrationTest)) {
tasks.getByPath(':spring-security-samples-casserver:casServerOverlay').logLevel = 'ERROR'
jettyRunWar {
additionalRuntimeJars += file("src/integration-test/resources")
daemon = true
}
[jettyRunWar.httpConnector,jettyRunWar.httpsConnector,casServer.httpsConnector]*.metaClass*.reservePort { taskToCloseSocket ->
def serverSocket = new ServerSocket(0)
delegate.metaClass.serverSocket = serverSocket
delegate.port = serverSocket.localPort
taskToCloseSocket.doFirst {
serverSocket.close()
}
}
[jettyRunWar.httpConnector,jettyRunWar.httpsConnector]*.reservePort(jettyRunWar)
jettyRunWar.httpConnector.confidentialPort = jettyRunWar.httpsConnector.port
casServer.httpsConnector.reservePort(casServer)
}
}
def casServer() {
tasks.getByPath(':spring-security-samples-casserver:casServer')
}
+175
View File
@@ -0,0 +1,175 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-samples-cassample-xml</artifactId>
<version>3.2.0.CI-SNAPSHOT</version>
<name>spring-security-samples-cassample-xml</name>
<description>spring-security-samples-cassample-xml</description>
<url>http://springsource.org/spring-security</url>
<organization>
<name>SpringSource</name>
<url>http://springsource.org/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@vmware.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/SpringSource/spring-security</connection>
<developerConnection>scm:git:git://github.com/SpringSource/spring-security</developerConnection>
<url>https://github.com/SpringSource/spring-security</url>
</scm>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.1.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>3.2.0.CI-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.0.CI-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.33</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.29</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.6.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.0.CI-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.0.CI-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.0.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>8.1.9.v20130131</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>8.1.9.v20130131</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gebish</groupId>
<artifactId>geb-spock</artifactId>
<version>0.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.33.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,30 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas;
import java.io.File;
import geb.spock.*
/**
* Base test for Geb testing.
*
* @author Rob Winch
*/
class AbstractCasTests extends GebReportingSpec {
}
@@ -0,0 +1,122 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod
import org.jasig.cas.client.jaas.CasLoginModule;
import org.jasig.cas.client.proxy.Cas20ProxyRetriever
import org.springframework.security.samples.cas.pages.*
import spock.lang.*
/**
* Tests authenticating to the CAS Sample application using Proxy Tickets. Geb is used to authenticate the {@link JettyCasService}
* to the CAS Server in order to obtain the Ticket Granting Ticket. Afterwards HttpClient is used for accessing the CAS Sample application
* using Proxy Tickets obtained using the Proxy Granting Ticket.
*
* @author Rob Winch
*/
@Stepwise
class CasSampleProxyTests extends AbstractCasTests {
HttpClient client = new HttpClient()
@Shared String casServerUrl = LoginPage.url.replaceFirst('/login','')
@Shared JettyCasService service = new JettyCasService().init(casServerUrl)
@Shared Cas20ProxyRetriever retriever = new Cas20ProxyRetriever(casServerUrl,'UTF-8')
@Shared String pt
def cleanupSpec() {
service.stop()
}
def 'access secure page succeeds with ROLE_USER'() {
setup: 'Obtain a pgt for a user with ROLE_USER'
driver.get LoginPage.url+"?service="+service.serviceUrl()
at LoginPage
login 'scott'
when: 'User with ROLE_USER accesses the secure page'
def content = getSecured(getBaseUrl()+SecurePage.url).responseBodyAsString
then: 'The secure page is returned'
content.contains('<h1>Secure Page</h1>')
}
def 'access proxy ticket sample succeeds with ROLE_USER'() {
when: 'a proxy ticket is used to create another proxy ticket'
def content = getSecured(getBaseUrl()+ProxyTicketSamplePage.url).responseBodyAsString
then: 'The proxy ticket sample page is returned'
content.contains('<h1>Secure Page using a Proxy Ticket</h1>')
}
def 'access extremely secure page with ROLE_USER is denied'() {
when: 'User with ROLE_USER accesses the extremely secure page'
GetMethod method = getSecured(getBaseUrl()+ExtremelySecurePage.url)
then: 'access is denied'
assert method.responseBodyAsString =~ /(?i)403.*?Denied/
assert 403 == method.statusCode
}
def 'access secure page with ROLE_SUPERVISOR succeeds'() {
setup: 'Obtain pgt for user with ROLE_SUPERVISOR'
to LocalLogoutPage
casServerLogout.click()
driver.get(LoginPage.url+"?service="+service.serviceUrl())
at LoginPage
login 'rod'
when: 'User with ROLE_SUPERVISOR accesses the secure page'
def content = getSecured(getBaseUrl()+ExtremelySecurePage.url).responseBodyAsString
then: 'The secure page is returned'
content.contains('<h1>VERY Secure Page</h1>')
}
def 'access extremely secure page with ROLE_SUPERVISOR reusing pt succeeds (stateless mode works)'() {
when: 'User with ROLE_SUPERVISOR accesses extremely secure page with used pt'
def content = getSecured(getBaseUrl()+ExtremelySecurePage.url,pt).responseBodyAsString
then: 'The extremely secure page is returned'
content.contains('<h1>VERY Secure Page</h1>')
}
def 'access secure page with invalid proxy ticket fails'() {
when: 'Invalid ticket is used to access secure page'
GetMethod method = getSecured(getBaseUrl()+SecurePage.url,'invalidticket')
then: 'Authentication fails'
method.statusCode == 401
}
/**
* Gets the result of calling a url with a proxy ticket
* @param targetUrl the absolute url to attempt to access
* @param pt the proxy ticket to use. Defaults to {@link #getPt(String)} with targetUrl specified for the targetUrl.
* @return the GetMethod after calling a url with a specified proxy ticket
*/
GetMethod getSecured(String targetUrl,String pt=getPt(targetUrl)) {
assert pt != null
GetMethod method = new GetMethod(targetUrl+"?ticket="+pt)
int status = client.executeMethod(method)
method
}
/**
* Obtains a proxy ticket using the pgt from the {@link #service}.
* @param targetService the targetService that the proxy ticket will be valid for
* @return a proxy ticket for targetService
*/
String getPt(String targetService) {
assert service.pgt != null
pt = retriever.getProxyTicketIdFor(service.pgt, targetService)
pt
}
}
@@ -0,0 +1,135 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas
import geb.spock.*
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.junit.runner.RunWith;
import org.spockframework.runtime.Sputnik;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy;
import org.springframework.security.samples.cas.pages.*
import spock.lang.Shared;
import spock.lang.Stepwise;
/**
* Tests the CAS sample application using service tickets.
*
* @author Rob Winch
*/
@Stepwise
class CasSampleTests extends AbstractCasTests {
@Shared String casServerLogoutUrl = LoginPage.url.replaceFirst('/login','/logout')
def 'access home page with unauthenticated user succeeds'() {
when: 'Unauthenticated user accesses the Home Page'
to HomePage
then: 'The home page succeeds'
at HomePage
}
def 'access extremely secure page with unauthenitcated user requires login'() {
when: 'Unauthenticated user accesses the extremely secure page'
via ExtremelySecurePage
then: 'The login page is displayed'
at LoginPage
}
def 'authenticate attempt with invaid ticket fails'() {
when: 'present invalid ticket'
go "j_spring_cas_security_check?ticket=invalid"
then: 'the login failed page is displayed'
$("h2").text() == 'Login to CAS failed!'
}
def 'access secure page with unauthenticated user requires login'() {
when: 'Unauthenticated user accesses the secure page'
via SecurePage
then: 'The login page is displayed'
at LoginPage
}
def 'saved request is used for secure page'() {
when: 'login with ROLE_USER after requesting the secure page'
login 'scott'
then: 'the secure page is displayed'
at SecurePage
}
def 'access proxy ticket sample with ROLE_USER is allowed'() {
when: 'user with ROLE_USER requests the proxy ticket sample page'
to ProxyTicketSamplePage
then: 'the proxy ticket sample page is displayed'
at ProxyTicketSamplePage
}
def 'access extremely secure page with ROLE_USER is denied'() {
when: 'User with ROLE_USER accesses extremely secure page'
via ExtremelySecurePage
then: 'the access denied page is displayed'
at AccessDeniedPage
}
def 'clicking local logout link displays local logout page'() {
setup: 'Navigate to page with logout link'
to SecurePage
when: 'Local logout link is clicked'
navModule.logout.click()
then: 'the local logout page is displayed'
at LocalLogoutPage
}
def 'clicking cas server logout link successfully performs logout'() {
when: 'the cas server logout link is clicked and the secure page is requested'
casServerLogout.click()
via SecurePage
then: 'the login page is displayed'
at LoginPage
}
def 'access extremely secure page with ROLE_SUPERVISOR succeeds'() {
setup: 'login with ROLE_SUPERVISOR'
login 'rod'
when: 'access extremely secure page'
to ExtremelySecurePage
then: 'extremely secure page is displayed'
at ExtremelySecurePage
}
def 'after logout extremely secure page requires login'() {
when: 'logout and request extremely secure page'
navModule.logout.click()
casServerLogout.click()
via ExtremelySecurePage
then: 'login page is displayed'
at LoginPage
}
def 'logging out of the cas server successfully logs out of the cas sample application'() {
setup: 'login with ROLE_USER'
via SecurePage
at LoginPage
login 'rod'
at SecurePage
when: 'logout of the CAS Server'
go casServerLogoutUrl
via SecurePage
then: 'user is logged out of the CAS Service'
at LoginPage
}
}
@@ -0,0 +1,124 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas;
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod;
import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.AbstractHandler
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.validation.Assertion
import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
/**
* A CAS Service that allows a PGT to be obtained. This is useful for testing use of proxy tickets.
*
* @author Rob Winch
*/
class JettyCasService extends Server {
private Cas20ProxyTicketValidator validator
private int port = availablePort()
/**
* The Proxy Granting Ticket. To initialize pgt, authenticate to the CAS Server with the service parameter
* equal to {@link #serviceUrl()}.
*/
String pgt
/**
* Start the CAS Service which will be available at {@link #serviceUrl()}.
*
* @param casServerUrl
* @return
*/
def init(String casServerUrl) {
ProxyGrantingTicketStorage storage = new ProxyGrantingTicketStorageImpl()
validator = new Cas20ProxyTicketValidator(casServerUrl)
validator.setAcceptAnyProxy(true)
validator.setProxyGrantingTicketStorage(storage)
validator.setProxyCallbackUrl(absoluteUrl('callback'))
String password = System.getProperty('javax.net.ssl.trustStorePassword','password')
SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector()
ssl_connector.setPort(port)
ssl_connector.setKeystore(getTrustStore())
ssl_connector.setPassword(password)
ssl_connector.setKeyPassword(password)
addConnector(ssl_connector)
setHandler(new AbstractHandler() {
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
def st = request.getParameter('ticket')
if(st) {
JettyCasService.this.validator.validate(st, JettyCasService.this.serviceUrl())
}
def pgt = request.getParameter('pgtId')
if(pgt) {
JettyCasService.this.pgt = pgt
}
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
}
})
start()
this
}
/**
* Returns the absolute URL that this CAS service is available at.
* @return
*/
String serviceUrl() {
absoluteUrl('service')
}
/**
* Given a relative url, will provide an absolute url for this CAS Service.
* @param relativeUrl the relative url (i.e. service, callback, etc)
* @return
*/
private String absoluteUrl(String relativeUrl) {
"https://localhost:${port}/${relativeUrl}"
}
private static String getTrustStore() {
String trustStoreLocation = System.getProperty('javax.net.ssl.trustStore')
if(trustStoreLocation == null || !new File(trustStoreLocation).isFile()) {
throw new IllegalStateException('Could not find the trust store at path "'+trustStoreLocation+'". Specify the location using the javax.net.ssl.trustStore system property.')
}
trustStoreLocation
}
/**
* Obtains a random available port (i.e. one that is not in use)
* @return
*/
private static int availablePort() {
ServerSocket server = new ServerSocket(0)
int port = server.localPort
server.close()
port
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.modules;
import geb.*
import org.springframework.security.samples.cas.pages.*
/**
* Represents the navigation for the CAS Sample application
*
* @author Rob Winch
*/
class NavModule extends Module {
static content = {
home(to: HomePage) { $("a", text: "Home") }
logout(to: LocalLogoutPage) { $("a", text: "Logout") }
}
}
@@ -0,0 +1,27 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
/**
* Represents the access denied page
*
* @author Rob Winch
*/
class AccessDeniedPage extends Page {
static at = { $("*",text: iContains(~/.*?403.*/)) }
}
@@ -0,0 +1,32 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
import org.springframework.security.samples.cas.modules.*
/**
* Represents the extremely secure page of the CAS Sample application.
*
* @author Rob Winch
*/
class ExtremelySecurePage extends Page {
static url = "secure/extreme/"
static at = { assert $('h1').text() == 'VERY Secure Page'; true; }
static content = {
navModule { module NavModule }
}
}
@@ -0,0 +1,32 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages
import geb.*
/**
* Represents the Home page of the CAS sample application
*
* @author Rob Winch
*/
class HomePage extends Page {
static at = { assert $('h1').text() == 'Home Page'; true}
static url = ''
static content = {
securePage { $('a',text: 'Secure page') }
extremelySecurePage { $('a',text: 'Extremely secure page') }
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
/**
* This represents the local logout page. This page is where the user is logged out of the CAS Sample application, but
* since the user is still logged into the CAS Server accessing a protected page within the CAS Sample application would result
* in SSO occurring again. To fully logout, the user should click the cas server logout url which logs out of the cas server and performs
* single logout on the other services.
*
* @author Rob Winch
*/
class LocalLogoutPage extends Page {
static url = 'cas-logout.jsp'
static at = { assert driver.currentUrl.endsWith(url); true }
static content = {
casServerLogout { $('a',text: 'Logout of CAS') }
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
/**
* The CAS login page.
*
* @author Rob Winch
*/
class LoginPage extends Page {
static url = loginUrl()
static at = { assert driver.currentUrl.startsWith(loginUrl()); true}
static content = {
login(required:false) { user, password=user ->
loginForm.username = user
loginForm.password = password
submit.click()
}
loginForm { $('#login') }
submit { $('input', type: 'submit') }
}
/**
* Gets the login page url which might change based upon the system properties. This is to support using a randomly available port for CI.
* @return
*/
private static String loginUrl() {
def host = System.getProperty('cas.server.host', 'localhost:9443')
"https://${host}/cas/login"
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
import org.springframework.security.samples.cas.modules.*
/**
* Represents the proxy ticket sample page within the CAS Sample application.
*
* @author Rob Winch
*/
class ProxyTicketSamplePage extends Page {
static url = "secure/ptSample"
static at = { assert $('h1').text() == 'Secure Page using a Proxy Ticket'; true}
static content = {
navModule { module NavModule }
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.pages;
import geb.*
import org.springframework.security.samples.cas.modules.*
/**
* Represents the secure page within the CAS Sample application.
*
* @author Rob Winch
*/
class SecurePage extends Page {
static url = "secure/"
static at = { assert $('h1').text() == 'Secure Page'; true}
static content = {
navModule { module NavModule }
}
}
@@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="error">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,79 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed 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 org.springframework.security.samples.cas.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.util.CommonUtils;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
/**
* <p>
* {@link ProxyTicketSampleServlet} demonstrates how to obtain a proxy ticket
* and then use it to make a remote call. To learn how proxy tickets work, see
* the <a href="https://wiki.jasig.org/display/CAS/Proxy+CAS+Walkthrough">Proxy
* CAS Walkthrough</a>
* </p>
*
* @author Rob Winch
*/
public final class ProxyTicketSampleServlet extends HttpServlet {
/**
* This is the URL that will be called and authenticate a proxy ticket.
*/
private String targetUrl;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NOTE: The CasAuthenticationToken can also be obtained using SecurityContextHolder.getContext().getAuthentication()
final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
// proxyTicket could be reused to make calls to to the CAS service even if the target url differs
final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);
// Make a remote call to ourself. This is a bit silly, but it works well to demonstrate how to use proxy tickets.
final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
// modify the response and write it out to inform the user that it was obtained using a proxy ticket.
proxyResponse = proxyResponse.replaceFirst("Secure Page", "Secure Page using a Proxy Ticket");
proxyResponse = proxyResponse.replaceFirst("<p>",
"<p>This page is rendered by "+getClass().getSimpleName()+" by making a remote call to the Secure Page using a proxy ticket ("+proxyTicket+") and inserts this message. ");
final PrintWriter writer = response.getWriter();
writer.write(proxyResponse);
}
/**
* Initialize the target URL. It allows for the host to change based upon
* the "cas.service.host" system property. If the property is not set, the
* default is "localhost:8443".
*/
@Override
public void init() throws ServletException {
super.init();
String casServiceHost = System.getProperty("cas.service.host", "localhost:8443");
targetUrl = "https://"+casServiceHost+"/cas-sample/secure/";
}
private static final long serialVersionUID = -7720161771819727775L;
}
@@ -0,0 +1,8 @@
<html>
<head>
<title>403 - Access Denied</title>
</head>
<body>
<h1>403 - Access Denied</h1>
</body>
</html>
@@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
xmlns="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<http entry-point-ref="casEntryPoint" use-expressions="true">
<intercept-url pattern="/" access="permitAll"/>
<intercept-url pattern="/index.jsp" access="permitAll"/>
<intercept-url pattern="/cas-logout.jsp" access="permitAll"/>
<intercept-url pattern="/casfailed.jsp" access="permitAll"/>
<intercept-url pattern="/secure/extreme/**"
access="hasRole('ROLE_SUPERVISOR')" />
<intercept-url pattern="/secure/**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
<custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
<custom-filter ref="casFilter" position="CAS_FILTER" />
<logout logout-success-url="/cas-logout.jsp"/>
</http>
<authentication-manager alias="authManager">
<authentication-provider ref="casAuthProvider" />
</authentication-manager>
<user-service id="userService">
<user name="rod" password="rod" authorities="ROLE_SUPERVISOR,ROLE_USER" />
<user name="dianne" password="dianne" authorities="ROLE_USER" />
<user name="scott" password="scott" authorities="ROLE_USER" />
</user-service>
<!-- This filter handles a Single Logout Request from the CAS Server -->
<b:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>
<!-- This filter redirects to the CAS Server to signal Single Logout should be performed -->
<b:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"
p:filterProcessesUrl="/j_spring_cas_security_logout">
<b:constructor-arg value="https://${cas.server.host}/cas/logout"/>
<b:constructor-arg>
<b:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</b:constructor-arg>
</b:bean>
<b:bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties"
p:service="https://${cas.service.host}/cas-sample/j_spring_cas_security_check"
p:authenticateAllArtifacts="true"/>
<b:bean id="casEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"
p:serviceProperties-ref="serviceProperties" p:loginUrl="https://${cas.server.host}/cas/login" />
<b:bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter"
p:authenticationManager-ref="authManager"
p:serviceProperties-ref="serviceProperties"
p:proxyGrantingTicketStorage-ref="pgtStorage"
p:proxyReceptorUrl="/j_spring_cas_security_proxyreceptor">
<b:property name="authenticationDetailsSource">
<b:bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"/>
</b:property>
<b:property name="authenticationFailureHandler">
<b:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/casfailed.jsp"/>
</b:property>
</b:bean>
<!--
NOTE: In a real application you should not use an in memory implementation. You will also want
to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup()
-->
<b:bean id="pgtStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"/>
<b:bean id="casAuthProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider"
p:serviceProperties-ref="serviceProperties"
p:key="casAuthProviderKey">
<b:property name="authenticationUserDetailsService">
<b:bean
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<b:constructor-arg ref="userService" />
</b:bean>
</b:property>
<b:property name="ticketValidator">
<b:bean
class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator"
p:acceptAnyProxy="true"
p:proxyCallbackUrl="https://${cas.service.host}/cas-sample/j_spring_cas_security_proxyreceptor"
p:proxyGrantingTicketStorage-ref="pgtStorage">
<b:constructor-arg value="https://${cas.server.host}/cas" />
</b:bean>
</b:property>
<b:property name="statelessTicketCache">
<b:bean class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
<b:property name="cache">
<b:bean class="net.sf.ehcache.Cache"
init-method="initialise"
destroy-method="dispose">
<b:constructor-arg value="casTickets"/>
<b:constructor-arg value="50"/>
<b:constructor-arg value="true"/>
<b:constructor-arg value="false"/>
<b:constructor-arg value="3600"/>
<b:constructor-arg value="900"/>
</b:bean>
</b:property>
</b:bean>
</b:property>
</b:bean>
<!-- Configuration for the environment can be overriden by system properties -->
<context:property-placeholder system-properties-mode="OVERRIDE" properties-ref="environment"/>
<util:properties id="environment">
<b:prop key="cas.service.host">localhost:8443</b:prop>
<b:prop key="cas.server.host">localhost:9443</b:prop>
</util:properties>
</b:beans>
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Tutorial web application
-
-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Spring Security CAS Demo Application</display-name>
<!--
- Location of the XML file that defines the root application context
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>cas.root</param-value>
</context-param>
<!--
Include the character encoding Filter as per JASIG recommenation when doing Single Sign Out
https://wiki.jasig.org/display/CASC/Configuring+Single+Sign+Out
-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
Included to support Single Logout. Note that the SingleSignOutFilter is included in the
springSecurityFilterChain. However, it could also be placed as the first filter-mapping
in the web.xml
-->
<listener>
<listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener>
<!--
- Loads the root application context of this web app at startup.
- The application context is then available via
- WebApplicationContextUtils.getWebApplicationContext(servletContext).
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>ptSampleServlet</servlet-name>
<servlet-class>org.springframework.security.samples.cas.web.ProxyTicketSampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ptSampleServlet</servlet-name>
<url-pattern>/secure/ptSample</url-pattern>
</servlet-mapping>
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
</web-app>
@@ -0,0 +1,15 @@
<html>
<head>
<title>Single-sign out?</title>
</head>
<body>
<h2>Do you want to log out of CAS?</h2>
<p>You have logged out of this application, but may still have an active single-sign on session with CAS.</p>
<p><a href="j_spring_cas_security_logout">Logout of CAS</a></p>
</body>
</html>
@@ -0,0 +1,26 @@
<%@ page import="org.springframework.security.core.AuthenticationException" %>
<%@ page import="org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter" %>
<html>
<head>
<title>Login to CAS failed!</title>
</head>
<body>
<h2>Login to CAS failed!</h2>
<font color="red">
Your CAS credentials were rejected.<br/><br/>
Reason:
<%
Exception error = ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY));
if(error != null) {
%>
<%= error.getMessage() %>
<%
}
%>
</font>
</body>
</html>
@@ -0,0 +1,12 @@
<html>
<body>
<h1>Home Page</h1>
<p>Anyone can view this page.</p>
<p>Your principal object is....: <%= request.getUserPrincipal() %></p>
<p><a href="secure/index.jsp">Secure page</a></p>
<p><a href="secure/ptSample">Proxy Ticket Sample page</a></p>
<p><a href="secure/extreme/index.jsp">Extremely secure page</a></p>
</body>
</html>
@@ -0,0 +1,11 @@
<html>
<body>
<h1>VERY Secure Page</h1>
This is a protected page. You can only see me if you are a supervisor.
<p><a href="../../">Home</a>
<p><a href="../../secure/index.jsp">Secure page</a></p>
<p><a href="../../secure/ptSample">Proxy Ticket Sample page</a></p>
<p><a href="../../j_spring_security_logout">Logout</a>
</body>
</html>
@@ -0,0 +1,15 @@
<html>
<body>
<h1>Secure Page</h1>
<p>This is a protected page. You can get to me if you've been remembered,
or if you've authenticated this session.</p>
<%if (request.isUserInRole("ROLE_SUPERVISOR")) { %>
<p>You are a supervisor! You can therefore see the <a href="extreme/index.jsp">extremely secure page</a>.</p>
<% } %>
<p><a href="../">Home</a>
<p><a href="ptSample">Proxy Ticket Sample page</a></p>
<p><a href="../j_spring_security_logout">Logout</a>
</body>
</html>