Skip to content

Instantly share code, notes, and snippets.

@dsyer
Created October 27, 2011 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsyer/1319529 to your computer and use it in GitHub Desktop.
Save dsyer/1319529 to your computer and use it in GitHub Desktop.
SECOAUTH-145: split spraklr2
target/
*/src/main/*/META-INF/
.access_token
.result
.classpath
.project
.DS_Store
.settings/
*.iml
*.iws
*.ipr
.idea/
cargo-installs/
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[2.6.0.201104111100-PATCH]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
<config>src/main/webapp/WEB-INF/spring-servlet.xml</config>
</configs>
<configSets>
</configSets>
</beansProjectDescription>

Sparklr2 with Split Aplication Context

<%@ page import="org.springframework.security.core.AuthenticationException" %>
<%@ page import="org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException" %>
<%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Sparklr</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/style.css"/>"/>
</head>
<body>
<h1>Sparklr</h1>
<div id="content">
<% if (session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) != null && !(session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) instanceof UnapprovedClientAuthenticationException)) { %>
<div class="error">
<h2>Woops!</h2>
<p>Access could not be granted. (<%= ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage() %>)</p>
</div>
<% } %>
<c:remove scope="session" var="SPRING_SECURITY_LAST_EXCEPTION"/>
<authz:authorize ifAllGranted="ROLE_USER">
<h2>Please Confirm</h2>
<p>You hereby authorize "<c:out value="${client.clientId}"/>" to access your protected resources.</p>
<form id="confirmationForm" name="confirmationForm" action="<%=request.getContextPath()%>/oauth/authorize" method="POST">
<input name="user_oauth_approval" value="true" type="hidden"/>
<label><input name="authorize" value="Authorize" type="submit"></label>
</form>
<form id="denialForm" name="denialForm" action="<%=request.getContextPath()%>/oauth/authorize" method="POST">
<input name="user_oauth_approval" value="false" type="hidden"/>
<label><input name="deny" value="Deny" type="submit"></label>
</form>
</authz:authorize>
</div>
<div id="footer">Design by <a href="http://www.pyserwebdesigns.com" target="_blank">Pyser Web Designs</a></div>
</body>
</html>
package org.springframework.security.oauth.examples.sparklr.mvc;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientToken;
import org.springframework.security.oauth2.provider.code.UnconfirmedAuthorizationCodeClientToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
/**
* Controller for retrieving the model for and displaying the confirmation page
* for access to a protected resource.
*
* @author Ryan Heaton
*/
@Controller
@SessionAttributes(types = UnconfirmedAuthorizationCodeClientToken.class)
public class AccessConfirmationController {
private ClientDetailsService clientDetailsService;
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(UnconfirmedAuthorizationCodeClientToken clientAuth) throws Exception {
ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
TreeMap<String, Object> model = new TreeMap<String, Object>();
model.put("auth_request", clientAuth);
model.put("client", client);
return new ModelAndView("access_confirmation", model);
}
@Autowired
public void setClientDetailsService(ClientDetailsService clientDetailsService) {
this.clientDetailsService = clientDetailsService;
}
}
<!--
This file contains useful Ant definitions for users of App Engine.
To use these macrodefs and taskdefs, import the file into your own build.xml:
<property name="appengine.sdk.dir" location="/some_dir/appengine-java-sdk-trunk"/>
<import file="${appengine.sdk.dir}/config/user/ant-macros.xml"/>
For example uses of the macros, see the template project's build.xml.
-->
<project name="appengine-ant-macros">
<property name="appengine.sdk.home" location="${sdk.dir}"/>
<property name="appengine.tools.classpath"
location="${appengine.sdk.home}/lib/appengine-tools-api.jar"/>
<!--
A macrodef for dev_appserver. Use like:
<dev_appserver war="${war}"/>
-->
<macrodef name="dev_appserver" description="Runs the App Engine Development App Server">
<attribute name="war" description="The exploded war directory containing the application"/>
<attribute name="port" default="8080" description="The port the server starts on"/>
<attribute name="address" default="localhost" description="The interface the server binds to"/>
<element name="options" optional="true" description="Additional options for dev_appserver"/>
<element name="args" optional="true" description="Additional arguments for the java task"/>
<sequential>
<java classname="com.google.appengine.tools.KickStart"
classpath="${appengine.tools.classpath}"
fork="true">
<arg value="com.google.appengine.tools.development.DevAppServerMain"/>
<arg value="--port=@{port}"/>
<arg value="--address=@{address}"/>
<options/>
<arg value="@{war}"/>
<args/>
</java>
</sequential>
</macrodef>
<!--
A macrodef for appcfg. Use like:
<appcfg action="update" war="${war}"/>
-->
<macrodef name="appcfg" description="Manages an application">
<attribute name="war" description="The exploded war directory containing the application"/>
<attribute name="action" description="One of (update, rollback, update_indexes, request_logs)"/>
<element name="options" optional="true" description="Options for appcfg (such as --server, --num_days, etc...)"/>
<element name="args" optional="true" description="Additional arguments for the java task"/>
<sequential>
<java classname="com.google.appengine.tools.admin.AppCfg"
classpath="${appengine.tools.classpath}"
fork="true">
<arg value="--disable_prompt"/>
<options/>
<arg value="@{action}"/>
<arg value="@{war}"/>
<args/>
</java>
</sequential>
</macrodef>
<!--
A taskdef for ORM enhancement. Use like:
<enhance failonerror="true">
<classpath>
<pathelement path="${appengine.tools.classpath}"/>
<pathelement path="@{war}/WEB-INF/classes"/>
<fileset dir="@{war}/WEB-INF/lib" includes="*.jar"/>
</classpath>
<fileset dir="@{war}/WEB-INF/classes" includes="**/*.class"/>
</enhance>
Alternatively, use the <enhance_war/> macrodef below.
-->
<taskdef name="enhance"
classpath="${appengine.tools.classpath}"
classname="com.google.appengine.tools.enhancer.EnhancerTask"/>
<!--
A macrodef for ORM enhancement for a war. Use like:
<enhance_war war="${war}"/>
-->
<macrodef name="enhance_war" description="Run the ORM enhancer on an exploded war">
<attribute name="war" description="The exploded war directory containing the application"/>
<element name="args" optional="true" description="Additional arguments to the enhancer"/>
<sequential>
<enhance failonerror="true">
<args/>
<classpath>
<pathelement path="${appengine.tools.classpath}"/>
<pathelement path="@{war}/WEB-INF/classes"/>
<fileset dir="@{war}/WEB-INF/lib" includes="*.jar"/>
</classpath>
<fileset dir="@{war}/WEB-INF/classes" includes="**/*.class"/>
</enhance>
</sequential>
</macrodef>
</project>
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>${gae.application.name}</application>
<version>1</version>
<sessions-enabled>true</sessions-enabled>
</appengine-web-app>
<?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:oauth="http://www.springframework.org/schema/security/oauth2" xmlns:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<http access-denied-page="/login.jsp" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/photos" access="ROLE_USER,SCOPE_READ" />
<intercept-url pattern="/photos/**" access="ROLE_USER,SCOPE_READ" />
<intercept-url pattern="/trusted/**" access="ROLE_CLIENT,SCOPE_TRUST" />
<intercept-url pattern="/user/**" access="ROLE_USER,SCOPE_TRUST" />
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/oauth/authorize" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/oauth/**" access="ROLE_USER" />
<intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY,DENY_OAUTH" />
<form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp"
login-processing-url="/login.do" />
<logout logout-success-url="/index.jsp" logout-url="/logout.do" />
<anonymous />
<custom-filter ref="oauth2ProviderFilter" before="EXCEPTION_TRANSLATION_FILTER" />
</http>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider>
<user-service>
<user name="marissa" password="koala" authorities="ROLE_USER" />
<user name="paul" password="emu" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.RandomValueTokenServices">
<property name="tokenStore">
<bean class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
</property>
<property name="supportRefreshToken" value="true" />
</bean>
<oauth:resource-server id="oauth2ProviderFilter" resource-id="sparklr" token-services-ref="tokenServices" />
<sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
<!--you could also wire in the expression handler up at the layer of the http filters. See https://jira.springsource.org/browse/SEC-1452 -->
<sec:expression-handler ref="oauthExpressionHandler" />
</sec:global-method-security>
<oauth:expression-handler id="oauthExpressionHandler" />
</beans>
<project name="sparklr">
<fail unless="gae.sdk" message="You must specify a 'gae.sdk' property."/>
<property name="sdk.dir" location="${gae.sdk}"/>
<import file="ant-macros.xml"/>
<property name="war.dir" value="target/sparklr-2.0-SNAPSHOT"/>
<target name="runserver" description="Starts the development server.">
<dev_appserver war="${war.dir}" port="8080"/>
</target>
<target name="update" description="Uploads the application to App Engine.">
<appcfg action="update" war="${war.dir}"/>
</target>
<target name="update_indexes" description="Uploads just the datastore index configuration to App Engine.">
<appcfg action="update_indexes" war="${war.dir}"/>
</target>
<target name="rollback" description="Rolls back an interrupted application update.">
<appcfg action="rollback" war="${war.dir}"/>
</target>
<target name="request_logs" description="Downloads log data from App Engine for the application.">
<appcfg action="request_logs" war="${war.dir}">
<options>
<arg value="--num_days=5"/>
</options>
<args>
<arg value="logs.txt"/>
</args>
</appcfg>
</target>
</project>
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl
org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
<%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Sparklr</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/style.css"/>"/>
<authz:authorize ifAllGranted="ROLE_USER">
<script type='text/javascript'>
function pictureDisplay(json) {
for (var i = 0; i < json.photos.length; i++) {
var photo = json.photos[i];
document.write('<img src="photos/' + photo.id + '" alt="' + photo.name + '">');
}
}
</script>
</authz:authorize>
</head>
<body>
<h1>Sparklr</h1>
<div id="content">
<h2>Home</h2>
<p>This is a great site to store and view your photos. Unfortunately, we don't have any services
for printing your photos. For that, you'll have to go to <a href="http://localhost:8888/tonr/">Tonr.com</a>.</p>
<authz:authorize ifNotGranted="ROLE_USER">
<h2>Login</h2>
<form id="loginForm" name="loginForm" action="<c:url value="/login.do"/>" method="POST">
<p><label>Username: <input type='text' name='j_username' value="marissa"></label></p>
<p><label>Password: <input type='text' name='j_password' value="koala"></label></p>
<p><input name="login" value="Login" type="submit"></p>
</form>
</authz:authorize>
<authz:authorize ifAllGranted="ROLE_USER">
<div style="text-align: center"><form action="<c:url value="/logout.do"/>"><input type="submit" value="Logout"></form></div>
<h2>Your Photos</h2>
<p>
<script type='text/javascript' src='photos?callback=pictureDisplay&format=json'></script>
</p>
</authz:authorize>
</div>
<div id="footer">Design by <a href="http://www.pyserwebdesigns.com" target="_blank">Pyser Web Designs</a></div>
</body>
</html>
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE
("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE
OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS
OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE
OF SUCH TERMS AND CONDITIONS.
1. Definitions
a. "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia,
in which the Work in its entirety in unmodified form, along with a number of other
contributions, constituting separate and independent works in themselves, are assembled
into a collective whole. A work that constitutes a Collective Work will not be
considered a Derivative Work (as defined below) for the purposes of this License.
b. "Derivative Work" means a work based upon the Work or upon the Work and other
pre-existing works, such as a translation, musical arrangement, dramatization,
fictionalization, motion picture version, sound recording, art reproduction, abridgment,
condensation, or any other form in which the Work may be recast, transformed, or adapted,
except that a work that constitutes a Collective Work will not be considered a Derivative
Work for the purpose of this License. For the avoidance of doubt, where the Work is a
musical composition or sound recording, the synchronization of the Work in timed-relation
with a moving image ("synching") will be considered a Derivative Work for the purpose of
this License.
c. "Licensor" means the individual or entity that offers the Work under the terms of this
License.
d. "Original Author" means the individual or entity who created the Work.
e. "Work" means the copyrightable work of authorship offered under the terms of this
License.
f. "You" means an individual or entity exercising rights under this License who has not
previously violated the terms of this License with respect to the Work, or who has
received express permission from the Licensor to exercise rights under this License
despite a previous violation.
g. "License Elements" means the following high-level license attributes as selected by
Licensor and indicated in the title of this License: Attribution, ShareAlike.
2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights
arising from fair use, first sale or other limitations on the exclusive rights of the copyright
owner under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants
You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable
copyright) license to exercise the rights in the Work as stated below:
a. to reproduce the Work, to incorporate the Work into one or more Collective Works, and to
reproduce the Work as incorporated in the Collective Works;
b. to create and reproduce Derivative Works;
c. to distribute copies or phonorecords of, display publicly, perform publicly, and perform
publicly by means of a digital audio transmission the Work including as incorporated in
Collective Works;
d. to distribute copies or phonorecords of, display publicly, perform publicly, and perform
publicly by means of a digital audio transmission Derivative Works.
e. For the avoidance of doubt, where the work is a musical composition:
i. Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to
collect, whether individually or via a performance rights society (e.g. ASCAP, BMI,
SESAC), royalties for the public performance or public digital performance (e.g.
webcast) of the Work.
ii. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to
collect, whether individually or via a music rights society or designated agent (e.g.
Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover
version") and distribute, subject to the compulsory license created by 17 USC Section
115 of the US Copyright Act (or the equivalent in other jurisdictions).
f. Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is
a sound recording, Licensor waives the exclusive right to collect, whether individually
or via a performance-rights society (e.g. SoundExchange), royalties for the public
digital performance (e.g. webcast) of the Work, subject to the compulsory license created
by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
The above rights may be exercised in all media and formats whether now known or hereafter devised.
The above rights include the right to make such modifications as are technically necessary to
exercise the rights in other media and formats. All rights not expressly granted by Licensor are
hereby reserved.
4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by
the following restrictions:
a. You may distribute, publicly display, publicly perform, or publicly digitally perform the
Work only under the terms of this License, and You must include a copy of, or the Uniform
Resource Identifier for, this License with every copy or phonorecord of the Work You
distribute, publicly display, publicly perform, or publicly digitally perform. You may
not offer or impose any terms on the Work that alter or restrict the terms of this
License or the recipients' exercise of the rights granted hereunder. You may not
sublicense the Work. You must keep intact all notices that refer to this License and to
the disclaimer of warranties. You may not distribute, publicly display, publicly perform,
or publicly digitally perform the Work with any technological measures that control
access or use of the Work in a manner inconsistent with the terms of this License
Agreement. The above applies to the Work as incorporated in a Collective Work, but this
does not require the Collective Work apart from the Work itself to be made subject to the
terms of this License. If You create a Collective Work, upon notice from any Licensor You
must, to the extent practicable, remove from the Collective Work any reference to such
Licensor or the Original Author, as requested. If You create a Derivative Work, upon
notice from any Licensor You must, to the extent practicable, remove from the Derivative
Work any reference to such Licensor or the Original Author, as requested.
b. You may distribute, publicly display, publicly perform, or publicly digitally perform a
Derivative Work only under the terms of this License, a later version of this License
with the same License Elements as this License, or a Creative Commons iCommons license
that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.0
Japan). You must include a copy of, or the Uniform Resource Identifier for, this License
or other license specified in the previous sentence with every copy or phonorecord of
each Derivative Work You distribute, publicly display, publicly perform, or publicly
digitally perform. You may not offer or impose any terms on the Derivative Works that
alter or restrict the terms of this License or the recipients' exercise of the rights
granted hereunder, and You must keep intact all notices that refer to this License and to
the disclaimer of warranties. You may not distribute, publicly display, publicly perform,
or publicly digitally perform the Derivative Work with any technological measures that
control access or use of the Work in a manner inconsistent with the terms of this License
Agreement. The above applies to the Derivative Work as incorporated in a Collective Work,
but this does not require the Collective Work apart from the Derivative Work itself to be
made subject to the terms of this License.
c. If you distribute, publicly display, publicly perform, or publicly digitally perform the
Work or any Derivative Works or Collective Works, You must keep intact all copyright
notices for the Work and give the Original Author credit reasonable to the medium or
means You are utilizing by conveying the name (or pseudonym if applicable) of the
Original Author if supplied; the title of the Work if supplied; to the extent reasonably
practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be
associated with the Work, unless such URI does not refer to the copyright notice or
licensing information for the Work; and in the case of a Derivative Work, a credit
identifying the use of the Work in the Derivative Work (e.g., "French translation of the
Work by Original Author," or "Screenplay based on original Work by Original Author").
Such credit may be implemented in any reasonable manner; provided, however, that in the
case of a Derivative Work or Collective Work, at a minimum such credit will appear where
any other comparable authorship credit appears and in a manner at least as prominent as
such other comparable authorship credit.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO
REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR
OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A
PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE
PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL
LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE
OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
a. This License and the rights granted hereunder will terminate automatically upon any
breach by You of the terms of this License. Individuals or entities who have received
Derivative Works or Collective Works from You under this License, however, will not have
their licenses terminated provided such individuals or entities remain in full compliance
with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this
License.
b. Subject to the above terms and conditions, the license granted here is perpetual (for the
duration of the applicable copyright in the Work). Notwithstanding the above, Licensor
reserves the right to release the Work under different license terms or to stop
distributing the Work at any time; provided, however that any such election will not
serve to withdraw this License (or any other license that has been, or is required to be,
granted under the terms of this License), and this License will continue in full force
and effect unless terminated as stated above.
8. Miscellaneous
a. Each time You distribute or publicly digitally perform the Work or a Collective Work, the
Licensor offers to the recipient a license to the Work on the same terms and conditions
as the license granted to You under this License.
b. Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers
to the recipient a license to the original Work on the same terms and conditions as the
license granted to You under this License.
c. If any provision of this License is invalid or unenforceable under applicable law, it
shall not affect the validity or enforceability of the remainder of the terms of this
License, and without further action by the parties to this agreement, such provision
shall be reformed to the minimum extent necessary to make such provision valid and
enforceable.
d. No term or provision of this License shall be deemed waived and no breach consented to
unless such waiver or consent shall be in writing and signed by the party to be charged
with such waiver or consent.
e. This License constitutes the entire agreement between the parties with respect to the
Work licensed here. There are no understandings, agreements or representations with
respect to the Work not specified here. Licensor shall not be bound by any additional
provisions that may appear in any communication from You. This License may not be
modified without the mutual written agreement of the Licensor and You.
Creative Commons is not a party to this License, and makes no warranty whatsoever in connection
with the Work. Creative Commons will not be liable to You or any party on any legal theory for
any damages whatsoever, including without limitation any general, special, incidental or
consequential damages arising in connection to this license. Notwithstanding the foregoing two
(2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder,
it shall have all rights and obligations of Licensor.
Except for the limited purpose of indicating to the public that the Work is licensed under the
CCPL, neither party will use the trademark "Creative Commons" or any related trademark or logo
of Creative Commons without the prior written consent of Creative Commons. Any permitted use will
be in compliance with Creative Commons' then-current trademark usage guidelines, as may be
published on its website or otherwise made available upon request from time to time.
Creative Commons may be contacted at http://creativecommons.org/.
<%@ page import="org.springframework.security.core.AuthenticationException" %>
<%@ page import="org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException" %>
<%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<authz:authorize ifAllGranted="ROLE_USER">
<c:redirect url="index.jsp"/>
</authz:authorize>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Sparklr</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/style.css"/>"/>
</head>
<body>
<h1>Sparklr</h1>
<div id="content">
<% if (session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) != null && !(session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) instanceof UnapprovedClientAuthenticationException)) { %>
<div class="error">
<h2>Woops!</h2>
<p>Your login attempt was not successful. (<%= ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage() %>)</p>
</div>
<% } %>
<c:remove scope="session" var="SPRING_SECURITY_LAST_EXCEPTION"/>
<authz:authorize ifNotGranted="ROLE_USER">
<h2>Login</h2>
<p>We've got a grand total of 2 users: marissa and paul. Go ahead and log in. Marissa's password is "koala" and Paul's password is "emu".</p>
<form id="loginForm" name="loginForm" action="<c:url value="/login.do"/>" method="POST">
<p><label>Username: <input type='text' name='j_username' value="marissa"></label></p>
<p><label>Password: <input type='text' name='j_password' value="koala"></label></p>
<p><input name="login" value="Login" type="submit"></p>
</form>
</authz:authorize>
</div>
<div id="footer">Design by <a href="http://www.pyserwebdesigns.com" target="_blank">Pyser Web Designs</a></div>
</body>
</html>
package org.springframework.security.oauth.examples.sparklr.mvc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth.examples.sparklr.PhotoInfo;
import org.springframework.security.oauth.examples.sparklr.PhotoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Ryan Heaton
* @author Dave Syer
*/
@Controller
public class PhotoController {
private PhotoService photoService;
@RequestMapping("/photos/{photoId}")
public ResponseEntity<byte[]> getPhoto(@PathVariable("photoId") String id) throws IOException {
InputStream photo = getPhotoService().loadPhoto(id);
if (photo == null) {
return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
} else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = photo.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = photo.read(buffer);
}
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");
return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
}
}
@RequestMapping(value = "/photos", params = "format=json")
public ResponseEntity<String> getJsonPhotos(@RequestParam(value = "callback", required = false) String callback, Principal principal) {
Collection<PhotoInfo> photos = getPhotoService().getPhotosForCurrentUser(principal.getName());
StringBuilder out = new StringBuilder();
if (callback != null) {
out.append(callback).append("( ");
}
out.append("{ \"photos\" : [ ");
Iterator<PhotoInfo> photosIt = photos.iterator();
while (photosIt.hasNext()) {
PhotoInfo photo = photosIt.next();
out.append(String.format("{ \"id\" : \"%s\" , \"name\" : \"%s\" }", photo.getId(), photo.getName()));
if (photosIt.hasNext()) {
out.append(" , ");
}
}
out.append("] }");
if (callback != null) {
out.append(" )");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
return new ResponseEntity<String>(out.toString(), headers, HttpStatus.OK);
}
@RequestMapping(value = "/photos", params = "format=xml")
public ResponseEntity<String> getXmlPhotos(Principal principal) {
Collection<PhotoInfo> photos = photoService.getPhotosForCurrentUser(principal.getName());
StringBuilder out = new StringBuilder();
out.append("<photos>");
for (PhotoInfo photo : photos) {
out.append(String.format("<photo id=\"%s\" name=\"%s\"/>", photo.getId(), photo.getName()));
}
out.append("</photos>");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/xml");
return new ResponseEntity<String>(out.toString(), headers, HttpStatus.OK);
}
@RequestMapping("/trusted/message")
@PreAuthorize("oauthClientHasRole('ROLE_CLIENT')")
@ResponseBody
public String getTrustedClientMessage() {
return "Hello, Trusted Client";
}
@RequestMapping("/user/message")
@ResponseBody
public String getTrustedUserMessage() {
return "Hello, Trusted User";
}
public PhotoService getPhotoService() {
return photoService;
}
public void setPhotoService(PhotoService photoService) {
this.photoService = photoService;
}
}
package org.springframework.security.oauth.examples.sparklr;
/**
* Photo information.
*
* @author Ryan Heaton
*/
public class PhotoInfo {
private String id;
private String resourceURL;
private String name;
private String userId;
/**
* Id of the photo.
*
* @return Id of the photo.
*/
public String getId() {
return id;
}
/**
* Id of the photo.
*
* @param id Id of the photo.
*/
public void setId(String id) {
this.id = id;
}
/**
* The resource URL.
*
* @return The resource URL.
*/
public String getResourceURL() {
return resourceURL;
}
/**
* The resource URL.
*
* @param resourceURL The resource URL
*/
public void setResourceURL(String resourceURL) {
this.resourceURL = resourceURL;
}
/**
* Name of the photo.
*
* @return Name of the photo.
*/
public String getName() {
return name;
}
/**
* Name of the photo.
*
* @param name Name of the photo.
*/
public void setName(String name) {
this.name = name;
}
/**
* The id of the user to whom the photo belongs.
*
* @return The id of the user to whom the photo belongs.
*/
public String getUserId() {
return userId;
}
/**
* The id of the user to whom the photo belongs.
*
* @param userId The id of the user to whom the photo belongs.
*/
public void setUserId(String userId) {
this.userId = userId;
}
}
package org.springframework.security.oauth.examples.sparklr;
import java.util.Collection;
import java.io.InputStream;
/**
* Service for retrieving photos.
*
* @author Ryan Heaton
*/
public interface PhotoService {
/**
* Load the photos for the current user.
*
* @return The photos for the current user.
*/
Collection<PhotoInfo> getPhotosForCurrentUser(String username);
/**
* Load a photo by id.
*
* @param id The id of the photo.
* @return The photo that was read.
*/
InputStream loadPhoto(String id);
}
package org.springframework.security.oauth.examples.sparklr.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth.examples.sparklr.PhotoInfo;
import org.springframework.security.oauth.examples.sparklr.PhotoService;
/**
* Basic implementation for the photo service.
*
* @author Ryan Heaton
*/
public class PhotoServiceImpl implements PhotoService {
private List<PhotoInfo> photos;
public Collection<PhotoInfo> getPhotosForCurrentUser(String username) {
ArrayList<PhotoInfo> infos = new ArrayList<PhotoInfo>();
for (PhotoInfo info : getPhotos()) {
if (username.equals(info.getUserId())) {
infos.add(info);
}
}
return infos;
}
public InputStream loadPhoto(String id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails details = (UserDetails) authentication.getPrincipal();
String username = details.getUsername();
for (PhotoInfo photoInfo : getPhotos()) {
if (id.equals(photoInfo.getId()) && username.equals(photoInfo.getUserId())) {
URL resourceURL = getClass().getResource(photoInfo.getResourceURL());
if (resourceURL != null) {
try {
return resourceURL.openStream();
} catch (IOException e) {
// fall through...
}
}
}
}
}
return null;
}
public List<PhotoInfo> getPhotos() {
return photos;
}
public void setPhotos(List<PhotoInfo> photos) {
this.photos = photos;
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth-parent</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
</parent>
<artifactId>sparklr2-split</artifactId>
<packaging>war</packaging>
<name>OAuth for Spring Security - Sparklr2 (OAuth 2 Provider Example)</name>
<properties>
<m2eclipse.wtp.contextRoot>sparklr</m2eclipse.wtp.contextRoot>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<!-- skip unit test run, tests to be executed during integration-test -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>surefire-it</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skip>${skipTests}</skip>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<id>start-container</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<wait>false</wait>
</configuration>
</execution>
<execution>
<id>stop-container</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
<configuration>
<skip>${skipTests}</skip>
<container>
<containerId>tomcat5x</containerId>
<zipUrlInstaller>
<url>http://archive.apache.org/dist/tomcat/tomcat-5/v5.5.26/bin/apache-tomcat-5.5.26.zip</url>
<installDir>${basedir}/cargo-installs</installDir>
</zipUrlInstaller>
<append>false</append>
</container>
<configuration>
<properties>
<!-- cargo.jvmargs>-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005</cargo.jvmargs -->
</properties>
<home>${project.build.directory}/tomcat5x</home>
<deployables>
<deployable>
<properties>
<context>sparklr</context>
</properties>
</deployable>
</deployables>
</configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<contextPath>/sparklr</contextPath>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopKey>sparklr</stopKey>
<stopPort>9999</stopPort>
</configuration>
</plugin>
<plugin>
<!--skip deploy (this is just a test module) -->
<artifactId>maven-deploy-plugin</artifactId>
<version>2.6</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Framework Milestone Repository</name>
<url>http://s3.amazonaws.com/maven.springframework.org/milestone</url>
</repository>
<repository>
<id>spring-release</id>
<name>Spring Framework Release Repository</name>
<url>http://maven.springframework.org/release</url>
</repository>
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- <profiles> <profile> <id>gae</id> <dependencies> <dependency> <groupId>com.google.appengine</groupId> <artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.2.2</version> </dependency> </dependencies> </profile> </profiles> -->
</project>
<%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Sparklr</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/style.css"/>"/>
</head>
<body>
<h1>Sparklr</h1>
<div id="content">
<h2>Home</h2>
<p>You have successfully authorized the request for a protected resource.</p>
</div>
<div id="footer">Design by <a href="http://www.pyserwebdesigns.com" target="_blank">Pyser Web Designs</a></div>
</body>
</html>
package org.springframework.security.oauth2.provider;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assume;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriTemplate;
import org.springframework.web.util.UriUtils;
/**
* <p> A rule that prevents integration tests from failing if the server application is not running or not accessible.
* If the server is not running in the background all the tests here will simply be skipped because of a violated
* assumption (showing as successful). Usage: </p>
*
* <pre> &#064;Rule public static BrokerRunning brokerIsRunning = BrokerRunning.isRunning();
*
* &#064;Test public void testSendAndReceive() throws Exception { // ... test using RabbitTemplate etc. } </pre> <p> The
* rule can be declared as static so that it only has to check once for all tests in the enclosing test case, but there
* isn't a lot of overhead in making it non-static. </p>
*
* @see Assume
* @see AssumptionViolatedException
*
* @author Dave Syer
*
*/
public class ServerRunning extends TestWatchman {
private static Log logger = LogFactory.getLog(ServerRunning.class);
// Static so that we only test once on failure: speeds up test suite
private static Map<Integer, Boolean> serverOnline = new HashMap<Integer, Boolean>();
// Static so that we only test once on failure
private static Map<Integer, Boolean> serverOffline = new HashMap<Integer, Boolean>();
private final boolean assumeOnline;
private static int DEFAULT_PORT = 8080;
private static String DEFAULT_HOST = "localhost";
private int port;
private String hostName = DEFAULT_HOST;
private RestTemplate client;
/**
* @return a new rule that assumes an existing running broker
*/
public static ServerRunning isRunning() {
return new ServerRunning(true);
}
/**
* @return a new rule that assumes there is no existing broker
*/
public static ServerRunning isNotRunning() {
return new ServerRunning(false);
}
private ServerRunning(boolean assumeOnline) {
this.assumeOnline = assumeOnline;
setPort(DEFAULT_PORT);
}
/**
* @param port the port to set
*/
public void setPort(int port) {
this.port = port;
if (!serverOffline.containsKey(port)) {
serverOffline.put(port, true);
}
if (!serverOnline.containsKey(port)) {
serverOnline.put(port, true);
}
client = getRestTemplate();
}
/**
* @param hostName the hostName to set
*/
public void setHostName(String hostName) {
this.hostName = hostName;
}
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
// Check at the beginning, so this can be used as a static field
if (assumeOnline) {
Assume.assumeTrue(serverOnline.get(port));
} else {
Assume.assumeTrue(serverOffline.get(port));
}
RestTemplate client = new RestTemplate();
boolean followRedirects = HttpURLConnection.getFollowRedirects();
HttpURLConnection.setFollowRedirects(false);
boolean online = false;
try {
client.getForEntity(new UriTemplate(getUrl("/sparklr/login.jsp")).toString(), String.class);
online = true;
logger.info("Basic connectivity test passed");
} catch (RestClientException e) {
logger.warn(String.format(
"Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
port), e);
if (assumeOnline) {
Assume.assumeNoException(e);
}
} finally {
HttpURLConnection.setFollowRedirects(followRedirects);
if (online) {
serverOffline.put(port, false);
if (!assumeOnline) {
Assume.assumeTrue(serverOffline.get(port));
}
} else {
serverOnline.put(port, false);
}
}
return super.apply(base, method, target);
}
public String getBaseUrl() {
return "http://" + hostName + ":" + port;
}
public String getUrl(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return "http://" + hostName + ":" + port + path;
}
public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
headers), String.class);
}
public ResponseEntity<String> postForString(String path, HttpHeaders headers, MultiValueMap<String, String> formData) {
HttpHeaders actualHeaders = new HttpHeaders();
actualHeaders.putAll(headers);
actualHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
actualHeaders), String.class);
}
public ResponseEntity<String> getForString(String path) {
return client.exchange(getUrl(path), HttpMethod.GET, new HttpEntity<Void>((Void) null), String.class);
}
public HttpStatus getStatusCode(String path, final HttpHeaders headers) {
RequestCallback requestCallback = new NullRequestCallback();
if (headers != null) {
requestCallback = new RequestCallback() {
public void doWithRequest(ClientHttpRequest request) throws IOException {
request.getHeaders().putAll(headers);
}
};
}
return client.execute(getUrl(path), HttpMethod.GET, requestCallback,
new ResponseExtractor<ResponseEntity<String>>() {
public ResponseEntity<String> extractData(ClientHttpResponse response) throws IOException {
return new ResponseEntity<String>(response.getStatusCode());
}
}).getStatusCode();
}
public HttpStatus getStatusCode(String path) {
return getStatusCode(getUrl(path), null);
}
public RestTemplate getRestTemplate() {
RestTemplate client = new RestTemplate();
CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory() {
@Override
protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) {
httpMethod.setFollowRedirects(false);
// We don't want stateful conversations for this test
httpMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
};
client.setRequestFactory(requestFactory);
client.setErrorHandler(new ResponseErrorHandler() {
// Pass errors through in response entity for status code analysis
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return client;
}
public UriBuilder buildUri(String url) {
return UriBuilder.fromUri(url.startsWith("http:") ? url : getUrl(url));
}
private static final class NullRequestCallback implements RequestCallback {
public void doWithRequest(ClientHttpRequest request) throws IOException {
}
}
public static class UriBuilder {
private final String url;
private MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
public UriBuilder(String url) {
this.url = url;
}
public static UriBuilder fromUri(String url) {
return new UriBuilder(url);
}
public UriBuilder queryParam(String key, String value) {
params.add(key, value);
return this;
}
public URI build() {
StringBuilder builder = new StringBuilder();
try {
builder.append(url.replace(" ", "+"));
if (!params.isEmpty()) {
builder.append("?");
boolean first = true;
for (String key : params.keySet()) {
if (!first) {
builder.append("&");
} else {
first = false;
}
for (String value : params.get(key)) {
builder.append(key + "=" + UriUtils.encodeQueryParam(value, "UTF-8"));
}
}
}
return new URI(builder.toString());
} catch (UnsupportedEncodingException ex) {
// should not happen, UTF-8 is always supported
throw new IllegalStateException(ex);
} catch (URISyntaxException ex) {
throw new IllegalArgumentException("Could not create URI from [" + builder + "]: " + ex, ex);
}
}
}
}
org.apache.commons.logging.simplelog.defaultlog=info
org.apache.commons.logging.simplelog.log.org.springframework.web=debug
org.apache.commons.logging.simplelog.log.org.springframework.security=debug
org.apache.commons.logging.simplelog.log.org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource=info
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="OAuth Contacts" scrolling="true">
<Require feature="opensocial-0.8" />
<Require feature="locked-domain"/>
<OAuth>
<Service name="google">
<Access url="${gae.application.url}/oauth/access_token" method="GET" />
<Request url="${gae.application.url}/oauth/request_token" method="GET" />
<Authorization url="${gae.application.url}/oauth/confirm_access?callbackURL=http://oauth.gmodules.com/gadgets/oauthcallback" />
</Service>
</OAuth>
</ModulePrefs>
<Content type="html">
<![CDATA[
<!-- shindig oauth popup handling code -->
<script src="http://gadget-doc-examples.googlecode.com/svn/trunk/opensocial-gadgets/popup.js"></script>
<style>
#main {
margin: 0px;
padding: 0px;
font-size: small;
}
</style>
<div id="main" style="display: none">
</div>
<div id="approval" style="display: none">
<img src="http://gadget-doc-examples.googlecode.com/svn/trunk/images/new.gif">
<a href="#" id="personalize">Personalize this gadget</a>
</div>
<div id="waiting" style="display: none">
Please click
<a href="#" id="approvaldone">I've approved access</a>
once you've approved access to your data.
</div>
<script type="text/javascript">
// Display UI depending on OAuth access state of the gadget (see <divs> above).
// If user hasn't approved access to data, provide a "Personalize this gadget" link
// that contains the oauthApprovalUrl returned from makeRequest.
//
// If the user has opened the popup window but hasn't yet approved access, display
// text prompting the user to confirm that s/he approved access to data. The user
// may not ever need to click this link, if the gadget is able to automatically
// detect when the user has approved access, but showing the link gives users
// an option to fetch their data even if the automatic detection fails.
//
// When the user confirms access, the fetchData() function is invoked again to
// obtain and display the user's data.
function showOneSection(toshow) {
var sections = [ 'main', 'approval', 'waiting' ];
for (var i=0; i < sections.length; ++i) {
var s = sections[i];
var el = document.getElementById(s);
if (s === toshow) {
el.style.display = "block";
} else {
el.style.display = "none";
}
}
}
// Process returned JSON feed to display data.
function showResults(result) {
showOneSection('main');
var titleElement = document.createElement('div');
var nameNode = document.createTextNode("some photos");
titleElement.appendChild(nameNode);
document.getElementById("main").appendChild(titleElement);
document.getElementById("main").appendChild(document.createElement("br"));
list = result.photos;
for(var i = 0; i < list.length; i++) {
entry = list[i];
var divElement = document.createElement('div');
divElement.setAttribute('class', 'name');
var valueNode = document.createTextNode(entry.name);
divElement.appendChild(nameNode);
divElement.appendChild(valueNode);
document.getElementById("main").appendChild(divElement);
}
}
// Invoke makeRequest() to fetch data from the service provider endpoint.
// Depending on the results of makeRequest, decide which version of the UI
// to ask showOneSection() to display. If user has approved access to his
// or her data, display data.
// If the user hasn't approved access yet, response.oauthApprovalUrl contains a
// URL that includes a Google-supplied request token. This is presented in the
// gadget as a link that the user clicks to begin the approval process.
function fetchData() {
var params = {};
url = "${gae.application.url}/json/photos";
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always";
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(url, function (response) {
if (response.oauthApprovalUrl) {
// Create the popup handler. The onOpen function is called when the user
// opens the popup window. The onClose function is called when the popup
// window is closed.
var popup = shindig.oauth.popup({
destination: response.oauthApprovalUrl,
windowOptions: null,
onOpen: function() { showOneSection('waiting'); },
onClose: function() { fetchData(); }
});
// Use the popup handler to attach onclick handlers to UI elements. The
// createOpenerOnClick() function returns an onclick handler to open the
// popup window. The createApprovedOnClick function returns an onclick
// handler that will close the popup window and attempt to fetch the user's
// data again.
var personalize = document.getElementById('personalize');
personalize.onclick = popup.createOpenerOnClick();
var approvaldone = document.getElementById('approvaldone');
approvaldone.onclick = popup.createApprovedOnClick();
showOneSection('approval');
} else if (response.data) {
showOneSection('main');
showResults(response.data);
} else {
// The response.oauthError and response.oauthErrorText values may help debug
// problems with your gadget.
var main = document.getElementById('main');
var err = document.createTextNode('OAuth error: ' +
response.oauthError + ': ' + response.oauthErrorText);
main.appendChild(err);
showOneSection('main');
}
}, params);
}
// Call fetchData() when gadget loads.
gadgets.util.registerOnLoadHandler(fetchData);
</script>
]]>
</Content>
</Module>
<?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:oauth="http://www.springframework.org/schema/security/oauth2" xmlns:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:client-details-service id="clientDetails">
<oauth:client clientId="my-trusted-client" authorizedGrantTypes="password,authorization_code,refresh_token,implicit"
authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT" scope="read,write,trust" />
<oauth:client clientId="my-trusted-client-with-secret" authorizedGrantTypes="password,authorization_code,refresh_token"
secret="somesecret" authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT" />
<oauth:client clientId="my-less-trusted-client" authorizedGrantTypes="authorization_code,implicit"
authorities="ROLE_CLIENT" />
<oauth:client clientId="my-client-with-registered-redirect" authorizedGrantTypes="authorization_code,client_credentials"
authorities="ROLE_CLIENT" redirect-uri="http://anywhere" scope="trust" />
<oauth:client clientId="my-untrusted-client-with-registered-redirect" authorizedGrantTypes="authorization_code"
authorities="ROLE_CLIENT" redirect-uri="http://anywhere" scope="read" />
<oauth:client clientId="tonr" resource-ids="sparklr" authorizedGrantTypes="authorization_code"
authorities="ROLE_CLIENT" scope="read,write" secret="secret" />
</oauth:client-details-service>
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<!--Basic application beans. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="photoController" class="org.springframework.security.oauth.examples.sparklr.mvc.PhotoController">
<property name="photoService" ref="photoServices" />
</bean>
<bean id="accessConfirmationController" class="org.springframework.security.oauth.examples.sparklr.mvc.AccessConfirmationController">
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="photoServices" class="org.springframework.security.oauth.examples.sparklr.impl.PhotoServiceImpl">
<property name="photos">
<list>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="1" />
<property name="name" value="photo1.jpg" />
<property name="userId" value="marissa" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo1.jpg" />
</bean>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="2" />
<property name="name" value="photo2.jpg" />
<property name="userId" value="paul" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo2.jpg" />
</bean>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="3" />
<property name="name" value="photo3.jpg" />
<property name="userId" value="marissa" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo3.jpg" />
</bean>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="4" />
<property name="name" value="photo4.jpg" />
<property name="userId" value="paul" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo4.jpg" />
</bean>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="5" />
<property name="name" value="photo5.jpg" />
<property name="userId" value="marissa" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo5.jpg" />
</bean>
<bean class="org.springframework.security.oauth.examples.sparklr.PhotoInfo">
<property name="id" value="6" />
<property name="name" value="photo6.jpg" />
<property name="userId" value="paul" />
<property name="resourceURL" value="/org/springframework/security/oauth/examples/sparklr/impl/resources/photo6.jpg" />
</bean>
</list>
</property>
</bean>
</beans>
/* CSS Document */
body {
color: white;
font-family: 'Trebuchet MS', Helvetica, sans-serif;
font-size: 12px;
margin: 0 auto;
width: 736px;
background: url( 'images/bg.gif' );
}
#content {
background: #3d3d3d;
width: 676px;
margin-top: 20px;
padding: 0 30px 25px 30px;
}
a {
color: lightblue;
text-decoration: none;
}
a:hover {
color: red;
text-decoration: none;
}
h1 {
background: url( 'images/header.jpg' );
height: 36px;
width: 721px;
margin: 0 0 1em 0;
padding-top: 80px;
padding-left: 15px;
font-size: 1.8em;
font-variant: small-caps;
}
h2 {
font-size: 1.2em;
margin-left: -10px;
padding-top: 20px;
font-weight: bold;
letter-spacing: .3px;
}
.error h2 {
color: red;
font-size: 1.2em;
padding-top: 20px;
font-weight: bold;
letter-spacing: .3px;
}
.error p {
color: red;
}
p {
letter-spacing: .2px;
}
label {
text-indent: 20px;
letter-spacing: .2px;
padding: 5px 5px 5px 5px;
}
#footer {
font-size: .8em;
margin-top: 1em;
}
#footer a {
color: #333333;
font-weight: bold;
font-size: 1em
}
#footer a:hover {
color: red;
font-weight: bold;
font-size: 1em
}
package org.springframework.security.oauth2.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.StringTokenizer;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.DefaultOAuth2SerializationService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.RedirectMismatchException;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
/**
* @author Ryan Heaton
* @author Dave Syer
*/
public class TestAuthorizationCodeProvider {
@Rule
public ServerRunning serverRunning = ServerRunning.isRunning();
/**
* tests the basic authorization code provider
*/
@Test
public void testBasicAuthorizationCodeProvider() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-less-trusted-client")
.queryParam("redirect_uri", "http://anywhere").queryParam("scope", "read").build();
String location = null;
try {
userAgent.getPage(uri.toString());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm okForm = confirmationPage.getFormByName("confirmationForm");
try {
((HtmlSubmitInput) okForm.getInputByName("authorize")).click();
fail("should have been redirected to the redirect page.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
URI redirection = serverRunning.buildUri(location).build();
assertEquals("anywhere", redirection.getHost());
assertEquals("http", redirection.getScheme());
assertNotNull(redirection.getQuery());
String code = null;
String state = null;
for (StringTokenizer queryTokens = new StringTokenizer(redirection.getQuery(), "&="); queryTokens
.hasMoreTokens();) {
String token = queryTokens.nextToken();
if ("code".equals(token)) {
if (code != null) {
fail("shouldn't have returned more than one code.");
}
code = queryTokens.nextToken();
} else if ("state".equals(token)) {
state = queryTokens.nextToken();
}
}
assertEquals("mystateid", state);
assertNotNull(code);
// we've got the authorization code. now we should be able to get an access token.
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "authorization_code");
formData.add("client_id", "my-less-trusted-client");
formData.add("scope", "read");
formData.add("redirect_uri", "http://anywhere");
formData.add("code", code);
formData.add("state", state);
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// let's try that request again and make sure we can't re-use the authorization code...
response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
try {
throw serializationService.deserializeJsonError(new ByteArrayInputStream(response.getBody().getBytes()));
} catch (OAuth2Exception e) {
assertTrue(e instanceof InvalidGrantException);
}
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
/**
* tests failure of getting the access token if some params are missing
*/
@Test
public void testFailureIfSomeParametersAreMissing() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-less-trusted-client")
.queryParam("redirect_uri", "http://anywhere").build();
String location = null;
try {
userAgent.getPage(uri.toURL());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm okForm = confirmationPage.getFormByName("confirmationForm");
try {
((HtmlSubmitInput) okForm.getInputByName("authorize")).click();
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
URI redirection = serverRunning.buildUri(location).build();
assertEquals("anywhere", redirection.getHost());
assertEquals("http", redirection.getScheme());
assertNotNull(redirection.getQuery());
String code = null;
for (StringTokenizer queryTokens = new StringTokenizer(redirection.getQuery(), "&="); queryTokens
.hasMoreTokens();) {
String token = queryTokens.nextToken();
if ("code".equals(token)) {
if (code != null) {
fail("shouldn't have returned more than one code.");
}
code = queryTokens.nextToken();
}
}
assertNotNull(code);
// we've got the authorization code. now let's make sure we get an error if we attempt to use a different
// redirect uri
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "authorization_code");
formData.add("client_id", "my-less-trusted-client");
formData.add("redirect_uri", "http://nowhere");
formData.add("code", code);
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2Exception jsonError = serializationService.deserializeJsonError(new ByteArrayInputStream(response
.getBody().getBytes()));
assertTrue("should be a redirect uri mismatch", jsonError instanceof RedirectMismatchException);
}
/**
* tests what happens if the user fails to authorize a token.
*/
@Test
public void testUserFailsToAuthorize() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-less-trusted-client")
.queryParam("redirect_uri", "http://anywhere").build();
String location = null;
try {
userAgent.getPage(uri.toURL());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm nonoForm = confirmationPage.getFormByName("denialForm");
try {
((HtmlSubmitInput) nonoForm.getInputByName("deny")).click();
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
// System.err.println(location);
assertTrue(location.startsWith("http://anywhere"));
assertTrue(location.substring(location.indexOf('?')).contains("error=access_denied"));
assertTrue(location.contains("state=mystateid"));
}
/**
* tests what happens if the client id isn't provided.
*/
@Test
public void testNoClientIdProvided() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid")
// .queryParam("client_id", "my-less-trusted-client")
.queryParam("redirect_uri", "http://anywhere").build();
try {
userAgent.getPage(uri.toURL());
fail("should have been a bad request.");
} catch (FailingHttpStatusCodeException e) {
// It's a bad request
assertEquals(400, e.getResponse().getStatusCode());
}
}
/**
* tests what happens if the client id isn't provided.
*/
@Test
public void testNoClientIdProvidedAndNoRedirect() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI
uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").build();
// .queryParam("client_id", "my-less-trusted-client")
// .queryParam("redirect_uri", "http://anywhere");
try {
userAgent.getPage(uri.toURL());
fail("should have been a bad request.");
} catch (FailingHttpStatusCodeException e) {
// It's a bad request
assertEquals(400, e.getResponse().getStatusCode());
}
}
@Test
public void testRegisteredRedirectUri() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-client-with-registered-redirect")
.queryParam("scope", "read").build();
String location = null;
try {
userAgent.getPage(uri.toString());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm okForm = confirmationPage.getFormByName("confirmationForm");
try {
((HtmlSubmitInput) okForm.getInputByName("authorize")).click();
fail("should have been redirected to the redirect page.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
assertNotNull(location);
URI redirection = serverRunning.buildUri(location).build();
assertEquals("anywhere", redirection.getHost());
assertEquals("http", redirection.getScheme());
assertNotNull(redirection.getQuery());
String code = null;
String state = null;
for (StringTokenizer queryTokens = new StringTokenizer(redirection.getQuery(), "&="); queryTokens
.hasMoreTokens();) {
String token = queryTokens.nextToken();
if ("code".equals(token)) {
if (code != null) {
fail("shouldn't have returned more than one code.");
}
code = queryTokens.nextToken();
} else if ("state".equals(token)) {
state = queryTokens.nextToken();
}
}
assertEquals("mystateid", state);
assertNotNull(code);
// we've got the authorization code. now we should be able to get an access token.
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "client_credentials");
formData.add("client_id", "my-client-with-registered-redirect");
formData.add("scope", "trust");
formData.add("state", state);
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/trusted/message"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/trusted/message", headers));
}
@Test
public void testWrongStateProvided() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-client-with-registered-redirect")
.queryParam("scope", "read").build();
String location = null;
try {
userAgent.getPage(uri.toString());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm okForm = confirmationPage.getFormByName("confirmationForm");
try {
((HtmlSubmitInput) okForm.getInputByName("authorize")).click();
fail("should have been redirected to the redirect page.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
URI redirection = serverRunning.buildUri(location).build();
String code = null;
String state = null;
for (StringTokenizer queryTokens = new StringTokenizer(redirection.getQuery(), "&="); queryTokens
.hasMoreTokens();) {
String token = queryTokens.nextToken();
if ("code".equals(token)) {
if (code != null) {
fail("shouldn't have returned more than one code.");
}
code = queryTokens.nextToken();
} else if ("state".equals(token)) {
state = queryTokens.nextToken();
}
}
assertEquals("mystateid", state);
assertNotNull(code);
// we've got the authorization code. now we should be able to get an access token.
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "authorization_code");
formData.add("client_id", "my-client-with-registered-redirect");
formData.add("scope", "read");
formData.add("code", code);
formData.add("state", "nottherightstate");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2Exception jsonError = serializationService.deserializeJsonError(new ByteArrayInputStream(response
.getBody().getBytes()));
assertTrue("should be a state mismatch", jsonError instanceof InvalidRequestException);
}
@Test
public void testWrongRedirectUriProvided() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "code")
.queryParam("state", "mystateid").queryParam("client_id", "my-untrusted-client-with-registered-redirect")
.queryParam("scope", "read").build();
String location = null;
try {
userAgent.getPage(uri.toString());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage confirmationPage = userAgent.getPage(location);
HtmlForm okForm = confirmationPage.getFormByName("confirmationForm");
try {
((HtmlSubmitInput) okForm.getInputByName("authorize")).click();
fail("should have been redirected to the redirect page.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
URI redirection = serverRunning.buildUri(location).build();
assertEquals("anywhere", redirection.getHost());
assertEquals("http", redirection.getScheme());
assertNotNull(redirection.getQuery());
String code = null;
String state = null;
for (StringTokenizer queryTokens = new StringTokenizer(redirection.getQuery(), "&="); queryTokens
.hasMoreTokens();) {
String token = queryTokens.nextToken();
if ("code".equals(token)) {
if (code != null) {
fail("shouldn't have returned more than one code.");
}
code = queryTokens.nextToken();
} else if ("state".equals(token)) {
state = queryTokens.nextToken();
}
}
assertEquals("mystateid", state);
assertNotNull(code);
// we've got the authorization code. now we should be able to get an access token.
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "authorization_code");
formData.add("client_id", "my-untrusted-client-with-registered-redirect");
formData.add("scope", "read");
formData.add("redirect_uri", "http://nowhere"); // should be ignored
formData.add("code", code);
formData.add("state", state);
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
}
}
/*
* Copyright 2006-2010 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.oauth2.provider;
import org.junit.Test;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
/**
* @author Dave Syer
*
*/
public class TestBootstrap {
@Test
public void testRootContext() throws Exception {
GenericXmlApplicationContext parent = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/applicationContext.xml"));
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.setParent(parent);
context.load(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
context.refresh();
context.close();
parent.close();
}
}
package org.springframework.security.oauth2.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;
import java.net.URI;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
/**
* @author Ryan Heaton
* @author Dave Syer
*/
public class TestImplicitProvider {
@Rule
public ServerRunning serverRunning = ServerRunning.isRunning();
/**
* tests the basic implicit provider
*/
@Test
public void testBasicImplicitProvider() throws Exception {
WebClient userAgent = new WebClient(BrowserVersion.FIREFOX_3);
userAgent.setRedirectEnabled(false);
URI uri = serverRunning.buildUri("/sparklr/oauth/authorize").queryParam("response_type", "token")
.queryParam("state", "mystateid").queryParam("client_id", "my-less-trusted-client")
.queryParam("redirect_uri", "http://anywhere").queryParam("scope", "read").build();
String location = null;
try {
userAgent.getPage(uri.toString());
fail("should have been redirected to the login form.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
HtmlPage loginPage = userAgent.getPage(location);
// should be directed to the login screen...
HtmlForm loginForm = loginPage.getFormByName("loginForm");
((HtmlTextInput) loginForm.getInputByName("j_username")).setValueAttribute("marissa");
((HtmlTextInput) loginForm.getInputByName("j_password")).setValueAttribute("koala");
try {
((HtmlSubmitInput) loginForm.getInputByName("login")).click();
fail("should have been redirected to the authorization endpoint.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
try {
userAgent.getPage(location);
fail("should have been redirected to the redirect page.");
} catch (FailingHttpStatusCodeException e) {
location = e.getResponse().getResponseHeaderValue("Location");
}
URI redirection = serverRunning.buildUri(location).build();
assertEquals("anywhere", redirection.getHost());
assertEquals("http", redirection.getScheme());
// we've got the access token.
String fragment = redirection.getFragment();
assertNotNull("No fragment in redirect: "+redirection, fragment);
String accessToken = null;
Long expiresIn = null;
String tokenType = null;
String[] parameters = fragment.split("&");
for (String parameter : parameters) {
String[] s=parameter.split("=");
String name=s[0];
String value=s[1];
if (name.equals("access_token")) {
accessToken = value;
} else if (name.equals("expires_in")) {
expiresIn = Long.valueOf(value);
} else if (name.equals("token_type")) {
tokenType = value;
}
}
assertNotNull(tokenType);
assertNotNull(expiresIn);
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
}
package org.springframework.security.oauth2.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.common.DefaultOAuth2SerializationService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author Ryan Heaton
* @author Dave Syer
*/
public class TestNativeApplicationProvider {
@Rule
public ServerRunning serverRunning = ServerRunning.isRunning();
/**
* tests a happy-day flow of the native application provider.
*/
@Test
public void testHappyDayWithForm() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client");
formData.add("scope", "read");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
/**
* tests a happy-day flow of the native application provider.
*/
@Test
public void testHappyDayWithHeader() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("scope", "read");
formData.add("username", "marissa");
formData.add("password", "koala");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization",
String.format("Basic %s", new String(Base64.encode("my-trusted-client:".getBytes("UTF-8")), "UTF-8")));
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", headers, formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
/**
* tests a happy-day flow of the native application profile.
*/
@Test
public void testSecretRequired() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client-with-secret");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
/**
* tests a happy-day flow of the native application provider.
*/
@Test
public void testSecretProvided() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client-with-secret");
formData.add("client_secret", "somesecret");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
/**
* tests a happy-day flow of the native application provider.
*/
@Test
public void testSecretProvidedInHeader() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("username", "marissa");
formData.add("password", "koala");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization",
"Basic " + new String(Base64.encode("my-trusted-client-with-secret:somesecret".getBytes())));
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", headers, formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
/**
* tests that an error occurs if you attempt to use username/password creds for a non-password grant type.
*/
@Test
public void testInvalidGrantType() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "authorization_code");
formData.add("client_id", "my-trusted-client");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
List<String> newCookies = response.getHeaders().get("Set-Cookie");
if (newCookies != null && !newCookies.isEmpty()) {
fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
}
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
try {
throw serializationService.deserializeJsonError(new ByteArrayInputStream(response.getBody().getBytes()));
} catch (OAuth2Exception e) {
assertEquals("invalid_request", e.getOAuth2ErrorCode());
}
}
/**
* tests a happy-day flow of the native application provider.
*/
@Test
public void testClientRoleBasedSecurity() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client");
formData.add("scope", "trust");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/user/message"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/user/message", headers));
}
}
package org.springframework.security.oauth2.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import java.io.ByteArrayInputStream;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.DefaultOAuth2SerializationService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author Ryan Heaton
* @author Dave Syer
*/
public class TestRefreshTokenSupport {
@Rule
public ServerRunning serverRunning = ServerRunning.isRunning();
/**
* tests a happy-day flow of the refresh token provider.
*/
@Test
public void testHappyDay() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client");
formData.add("scope", "read");
formData.add("username", "marissa");
formData.add("password", "koala");
ResponseEntity<String> response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
// now use the refresh token to get a new access token.
assertNotNull(accessToken.getRefreshToken());
formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "refresh_token");
formData.add("client_id", "my-trusted-client");
formData.add("refresh_token", accessToken.getRefreshToken().getValue());
response = serverRunning.postForString("/sparklr/oauth/token", formData);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
OAuth2AccessToken newAccessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
assertFalse(newAccessToken.getValue().equals(accessToken.getValue()));
// make sure the new access token can be used.
headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, newAccessToken.getValue()));
assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
// make sure the old access token isn't valid anymore.
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
assertEquals(HttpStatus.UNAUTHORIZED, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment