Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 32abe39afe | |||
| 102da87080 | |||
| f1ae9da55e | |||
| 94e2e0c65e | |||
| fa3a30cc20 | |||
| ee6e6ceafb | |||
| 095594daea | |||
| e9215c4dc3 | |||
| 0d70c703df | |||
| 73710bf7b8 | |||
| ca5501eb31 | |||
| c703806fa2 | |||
| 67eb9821f3 | |||
| 7b93ffd5d4 | |||
| 5fa252b848 | |||
| 87c3c7edb9 | |||
| 7f342f3321 | |||
| 2f6325f651 | |||
| e3f53908af | |||
| 4d1127106b |
+186
@@ -0,0 +1,186 @@
|
||||
_Have something you'd like to contribute to the framework? We welcome pull requests, but ask that you carefully read this document first to understand how best to submit them; what kind of changes are likely to be accepted; and what to expect from the Spring Security team when evaluating your submission._
|
||||
|
||||
_Please refer back to this document as a checklist before issuing any pull request; this will save time for everyone!_
|
||||
|
||||
# Similar but different
|
||||
|
||||
Each Spring module is slightly different than another in terms of team size, number of issues, etc. Therefore each project is managed slightly different. You will notice that this document is very similar to the [Spring Framework Contributor guidelines](https://github.com/SpringSource/spring-framework/wiki/Contributor-guidelines). However, there are some subtle differences between the two documents, so please be sure to read this document thoroughly.
|
||||
|
||||
# Understand the basics
|
||||
Not sure what a pull request is, or how to submit one? Take a look at GitHub's excellent [help documentation first](http://help.github.com/send-pull-requests).
|
||||
|
||||
# Search JIRA first; create an issue if necessary
|
||||
Is there already an issue that addresses your concern? Do a bit of searching in our [JIRA issue tracker](https://jira.springsource.org/browse/SEC) to see if you can find something similar. If not, please create a new issue before submitting a pull request unless the change is not a user facing issue.
|
||||
|
||||
# Discuss non-trivial contribution ideas with committers
|
||||
If you're considering anything more than correcting a typo or fixing a minor bug , please discuss it on the [Spring Security forums](http://forum.springsource.org/forumdisplay.php?33-Security) before submitting a pull request. We're happy to provide guidance but please spend an hour or two researching the subject on your own including searching the forums for prior discussions.
|
||||
|
||||
# Sign the Contributor License Agreement
|
||||
If you have not previously done so, please fill out and submit the SpringSource CLA form. You'll receive a token when this process is complete. Keep track of this, you may be asked for it later!
|
||||
|
||||
* For **Project** select _Spring Security_
|
||||
* For **Project Lead** enter _Rob Winch_
|
||||
* Note that emailing/postal mailing a signed copy is not necessary. Submission of the web form is all that is required.
|
||||
|
||||
When you've completed the web form, simply add the following in a comment on your pull request:
|
||||
|
||||
> I have signed and agree to the terms of the SpringSource Individual Contributor License Agreement.
|
||||
|
||||
You do not need to include your token/id. Please add the statement above to all future pull requests as well, simply so the Spring Security team knows immediately that this process is complete.
|
||||
|
||||
# Create your branch from master
|
||||
Create your topic branch to be submitted as a pull request from master. The Spring team will consider your pull request for backporting on a case-by-case basis; you don't need to worry about submitting anything for backporting.
|
||||
|
||||
# Use short branch names
|
||||
Branches used when submitting pull requests should preferably be named according to JIRA issues, e.g. 'SEC-1234'. Otherwise, use succinct, lower-case, dash (-) delimited names, such as 'fix-warnings', 'fix-typo', etc. This is important, because branch names show up in the merge commits that result from accepting pull requests, and should be as expressive and concise as possible.
|
||||
|
||||
#Keep commits focused
|
||||
|
||||
Remember each JIRA should be focused on a single item of interest since the JIRA tickets are used to produce the changelog. Since each commit should be tied to a JIRA, ensure that your commits are focused. For example, do not include an update to a transitive library in your commit unless the JIRA is to update the library. Reviewing your commits is essential before sending a pull request.
|
||||
|
||||
# Mind the whitespace
|
||||
Please carefully follow the whitespace and formatting conventions already present in the framework.
|
||||
|
||||
1. Spaces, not tabs
|
||||
1. Unix (LF), not dos (CRLF) line endings
|
||||
1. Eliminate all trailing whitespace
|
||||
1. Aim to wrap code at 120 characters, but favor readability over wrapping
|
||||
1. Preserve existing formatting; i.e. do not reformat code for its own sake
|
||||
1. Search the codebase using git grep and other tools to discover common naming conventions, etc.
|
||||
1. Latin-1 (ISO-8859-1) encoding for Java sources; use native2ascii to convert if necessary
|
||||
|
||||
Whitespace management tips
|
||||
|
||||
1. You can use the [AnyEdit Eclipse plugin](http://marketplace.eclipse.org/content/anyedit-tools) to ensure spaces are used and to clean up trailing whitespaces.
|
||||
1. Use git's pre-commit.sample hook to prevent invalid whitespace from being pushed out. You can enable it by moving ~/spring-security/.git/hooks/pre-commit.sample to ~/spring-security/.git/hooks/pre-commit and ensuring it is executable. For more information on hooks refer to [Pro Git's Pre-Commit Hook's section](http://git-scm.com/book/cs/ch7-3.html)
|
||||
|
||||
# Add Apache license header to all new classes
|
||||
|
||||
<pre>
|
||||
/*
|
||||
* Copyright 2002-2012 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 ...;
|
||||
</pre>
|
||||
# Update Apache license header to modified files as necessary
|
||||
Always check the date range in the license header. For example, if you've modified a file in 2012 whose header still reads
|
||||
<pre>
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
</pre>
|
||||
then be sure to update it to 2012 appropriately
|
||||
<pre>
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
</pre>
|
||||
# Use @since tags for newly-added public API types and methods
|
||||
e.g.
|
||||
<pre>
|
||||
/**
|
||||
* ...
|
||||
*
|
||||
* @author First Last
|
||||
* @since 3.2
|
||||
* @see ...
|
||||
*/
|
||||
</pre>
|
||||
|
||||
#Submit JUnit test cases for all behavior changes
|
||||
Search the codebase to find related unit tests and add additional `@Test` methods within.
|
||||
|
||||
1. Any new tests should end in the name Tests (note this is plural). For example, a valid name would be `FilterChainProxyTests`. An invalid name would be `FilterChainProxyTest`.
|
||||
2. New test methods should not start with test. This is an old JUnit3 convention and is not necessary since the method is annotated with @Test.
|
||||
|
||||
# Squash commits
|
||||
Use git rebase --interactive, git add --patch and other tools to "squash" multiple commits into atomic changes. In addition to the man pages for git, there are many resources online to help you understand how these tools work. Here is one: http://book.git-scm.com/4_interactive_rebasing.html.
|
||||
|
||||
# Use real name in git commits
|
||||
Please configure git to use your real first and last name for any commits you intend to submit as pull requests. For example, this is not acceptable:
|
||||
|
||||
<pre>
|
||||
Author: Nickname <user@mail.com>
|
||||
</pre>
|
||||
Rather, please include your first and last name, properly capitalized, as submitted against the SpringSource contributor license agreement:
|
||||
<pre>
|
||||
Author: First Last <user@mail.com>
|
||||
</pre>
|
||||
This helps ensure traceability against the CLA, and also goes a long way to ensuring useful output from tools like git shortlog and others.
|
||||
|
||||
You can configure this globally via the account admin area GitHub (useful for fork-and-edit cases); globally with
|
||||
|
||||
<pre>
|
||||
git config --global user.name "First Last"
|
||||
git config --global user.email user@mail.com
|
||||
</pre>
|
||||
|
||||
or locally for the spring-security repository only by omitting the '--global' flag:
|
||||
<pre>
|
||||
cd spring-security
|
||||
git config user.name "First Last"
|
||||
git config user.email user@mail.com
|
||||
</pre>
|
||||
|
||||
# Format commit messages
|
||||
|
||||
<pre>
|
||||
SEC-1234: Short (50 chars or less) summary of changes
|
||||
|
||||
More detailed explanatory text, if necessary. Wrap it to about 72
|
||||
characters or so. In some contexts, the first line is treated as the
|
||||
subject of an email and the rest of the text as the body. The blank
|
||||
line separating the summary from the body is critical (unless you omit
|
||||
the body entirely); tools like rebase can get confused if you run the
|
||||
two together.
|
||||
|
||||
Further paragraphs come after blank lines.
|
||||
|
||||
- Bullet points are okay, too
|
||||
|
||||
- Typically a hyphen or asterisk is used for the bullet, preceded by a
|
||||
single space, with blank lines in between, but conventions vary here
|
||||
</pre>
|
||||
|
||||
|
||||
1. The commit subject should start with the associated jira issue followed by a : as shown in the example above
|
||||
2. Keep the subject line to 50 characters or less if possible
|
||||
3. Do not end the subject line with a period
|
||||
4. In the body of the commit message, explain how things worked before this commit, what has changed, and how things work now
|
||||
|
||||
# Run all tests prior to submission
|
||||
|
||||
<pre>
|
||||
cd spring-security
|
||||
./gradlew clean build integrationTest
|
||||
</pre>
|
||||
|
||||
# Submit your pull request
|
||||
Subject line:
|
||||
|
||||
Follow the same conventions for pull request subject lines as mentioned above for commit message subject lines.
|
||||
|
||||
In the body:
|
||||
|
||||
1. Explain your use case. What led you to submit this change? Why were existing mechanisms in the framework insufficient? Make a case that this is a general-purpose problem and that yours is a general-purpose solution, etc
|
||||
2. Add any additional information and ask questions; start a conversation, or continue one from JIRA
|
||||
3. Mention the JIRA issue ID
|
||||
4. Also mention that you have submitted the CLA as described above
|
||||
Note that for pull requests containing a single commit, GitHub will default the subject line and body of the pull request to match the subject line and body of the commit message. This is fine, but please also include the items above in the body of the request.
|
||||
|
||||
# Mention your pull request on the associated JIRA issue
|
||||
Add a comment to the associated JIRA issue(s) linking to your new pull request.
|
||||
|
||||
# Expect discussion and rework
|
||||
The Spring team takes a very conservative approach to accepting contributions to the framework. This is to keep code quality and stability as high as possible, and to keep complexity at a minimum. Your changes, if accepted, may be heavily modified prior to merging. You will retain "Author:" attribution for your Git commits granted that the bulk of your changes remain intact. You may be asked to rework the submission for style (as explained above) and/or substance. Again, we strongly recommend discussing any serious submissions with the Spring Framework team prior to engaging in serious development work.
|
||||
|
||||
Note that you can always force push (git push -f) reworked / rebased commits against the branch used to submit your pull request. i.e. you do not need to issue a new pull request when asked to make changes.
|
||||
@@ -5,7 +5,6 @@ dependencies {
|
||||
'aopalliance:aopalliance:1.0',
|
||||
"net.sf.ehcache:ehcache:$ehcacheVersion",
|
||||
"org.springframework:spring-aop:$springVersion",
|
||||
"org.springframework:spring-beans:$springVersion",
|
||||
"org.springframework:spring-context:$springVersion",
|
||||
"org.springframework:spring-tx:$springVersion",
|
||||
"org.springframework:spring-jdbc:$springVersion"
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ allprojects {
|
||||
group = 'org.springframework.security'
|
||||
|
||||
repositories {
|
||||
maven { url "http://repo.springsource.org/libs-snapshot" }
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,5 +79,5 @@ artifacts {
|
||||
apply from: "$rootDir/gradle/ide-integration.gradle"
|
||||
|
||||
task wrapper(type: Wrapper) {
|
||||
gradleVersion = '1.3'
|
||||
gradleVersion = '1.2'
|
||||
}
|
||||
|
||||
+2
-2
@@ -8,5 +8,5 @@ dependencies {
|
||||
"org.jasig.cas.client:cas-client-core:3.1.12",
|
||||
"net.sf.ehcache:ehcache:$ehcacheVersion"
|
||||
|
||||
provided "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
}
|
||||
provided 'javax.servlet:servlet-api:2.5'
|
||||
}
|
||||
@@ -21,7 +21,7 @@ dependencies {
|
||||
"org.springframework:spring-web:$springVersion",
|
||||
"org.springframework:spring-beans:$springVersion"
|
||||
|
||||
provided "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
provided "javax.servlet:servlet-api:2.5"
|
||||
|
||||
groovy 'org.codehaus.groovy:groovy:1.8.7'
|
||||
|
||||
@@ -35,7 +35,12 @@ dependencies {
|
||||
"org.springframework:spring-tx:$springVersion",
|
||||
'org.spockframework:spock-core:0.6-groovy-1.8',
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
powerMockDependencies
|
||||
"org.powermock:powermock-core:$powerMockVersion",
|
||||
"org.powermock:powermock-api-support:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4-common:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4:$powerMockVersion",
|
||||
"org.powermock:powermock-api-mockito:$powerMockVersion",
|
||||
"org.powermock:powermock-reflect:$powerMockVersion"
|
||||
testCompile('org.openid4java:openid4java-nodeps:0.9.6') {
|
||||
exclude group: 'com.google.code.guice', module: 'guice'
|
||||
}
|
||||
|
||||
+1
-7
@@ -115,7 +115,6 @@ final class AuthenticationConfigBuilder {
|
||||
private BeanDefinition jeeFilter;
|
||||
private BeanReference jeeProviderRef;
|
||||
private RootBeanDefinition preAuthEntryPoint;
|
||||
private BeanMetadataElement mainEntryPoint;
|
||||
|
||||
private BeanDefinition logoutFilter;
|
||||
@SuppressWarnings("rawtypes")
|
||||
@@ -500,10 +499,6 @@ final class AuthenticationConfigBuilder {
|
||||
return logoutHandlers;
|
||||
}
|
||||
|
||||
BeanMetadataElement getEntryPointBean() {
|
||||
return mainEntryPoint;
|
||||
}
|
||||
|
||||
void createAnonymousFilter() {
|
||||
Element anonymousElt = DomUtils.getChildElementByTagName(httpElt, Elements.ANONYMOUS);
|
||||
|
||||
@@ -561,8 +556,7 @@ final class AuthenticationConfigBuilder {
|
||||
BeanDefinitionBuilder etfBuilder = BeanDefinitionBuilder.rootBeanDefinition(ExceptionTranslationFilter.class);
|
||||
etfBuilder.addPropertyValue("accessDeniedHandler", createAccessDeniedHandler(httpElt, pc));
|
||||
assert requestCache != null;
|
||||
mainEntryPoint = selectEntryPoint();
|
||||
etfBuilder.addConstructorArgValue(mainEntryPoint);
|
||||
etfBuilder.addConstructorArgValue(selectEntryPoint());
|
||||
etfBuilder.addConstructorArgValue(requestCache);
|
||||
|
||||
etf = etfBuilder.getBeanDefinition();
|
||||
|
||||
+5
-34
@@ -21,9 +21,6 @@ import static org.springframework.security.config.http.SecurityFilters.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.ServletRequest;
|
||||
|
||||
import org.springframework.beans.BeanMetadataElement;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanReference;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
@@ -56,7 +53,6 @@ import org.springframework.security.web.authentication.session.SessionFixationPr
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.security.web.context.NullSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
|
||||
import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.NullRequestCache;
|
||||
@@ -65,7 +61,6 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
import org.springframework.security.web.session.SessionManagementFilter;
|
||||
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.util.xml.DomUtils;
|
||||
import org.w3c.dom.Element;
|
||||
@@ -107,7 +102,6 @@ class HttpConfigurationBuilder {
|
||||
private BeanReference contextRepoRef;
|
||||
private BeanReference sessionRegistryRef;
|
||||
private BeanDefinition concurrentSessionFilter;
|
||||
private BeanDefinition webAsyncManagerFilter;
|
||||
private BeanDefinition requestCacheAwareFilter;
|
||||
private BeanReference sessionStrategyRef;
|
||||
private RootBeanDefinition sfpf;
|
||||
@@ -120,6 +114,7 @@ class HttpConfigurationBuilder {
|
||||
|
||||
public HttpConfigurationBuilder(Element element, ParserContext pc,
|
||||
BeanReference portMapper, BeanReference portResolver, BeanReference authenticationManager) {
|
||||
|
||||
this.httpElt = element;
|
||||
this.pc = pc;
|
||||
this.portMapper = portMapper;
|
||||
@@ -145,9 +140,8 @@ class HttpConfigurationBuilder {
|
||||
|
||||
createSecurityContextPersistenceFilter();
|
||||
createSessionManagementFilters();
|
||||
createWebAsyncManagerFilter();
|
||||
createRequestCacheFilter();
|
||||
createServletApiFilter(authenticationManager);
|
||||
createServletApiFilter();
|
||||
createJaasApiFilter();
|
||||
createChannelProcessingFilter();
|
||||
createFilterSecurityInterceptor(authenticationManager);
|
||||
@@ -155,19 +149,8 @@ class HttpConfigurationBuilder {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
void setLogoutHandlers(ManagedList logoutHandlers) {
|
||||
if(logoutHandlers != null) {
|
||||
if(concurrentSessionFilter != null) {
|
||||
concurrentSessionFilter.getPropertyValues().add("logoutHandlers", logoutHandlers);
|
||||
}
|
||||
if(servApiFilter != null) {
|
||||
servApiFilter.getPropertyValues().add("logoutHandlers", logoutHandlers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setEntryPoint(BeanMetadataElement entryPoint) {
|
||||
if(servApiFilter != null) {
|
||||
servApiFilter.getPropertyValues().add("authenticationEntryPoint", entryPoint);
|
||||
if(logoutHandlers != null && concurrentSessionFilter != null) {
|
||||
concurrentSessionFilter.getPropertyValues().add("logoutHandlers", logoutHandlers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,15 +350,8 @@ class HttpConfigurationBuilder {
|
||||
sessionRegistryRef = new RuntimeBeanReference(sessionRegistryId);
|
||||
}
|
||||
|
||||
private void createWebAsyncManagerFilter() {
|
||||
boolean asyncSupported = ClassUtils.hasMethod(ServletRequest.class, "startAsync");
|
||||
if(asyncSupported) {
|
||||
webAsyncManagerFilter = new RootBeanDefinition(WebAsyncManagerIntegrationFilter.class);
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the servlet-api integration filter if required
|
||||
private void createServletApiFilter(BeanReference authenticationManager) {
|
||||
private void createServletApiFilter() {
|
||||
final String ATT_SERVLET_API_PROVISION = "servlet-api-provision";
|
||||
final String DEF_SERVLET_API_PROVISION = "true";
|
||||
|
||||
@@ -386,7 +362,6 @@ class HttpConfigurationBuilder {
|
||||
|
||||
if ("true".equals(provideServletApi)) {
|
||||
servApiFilter = new RootBeanDefinition(SecurityContextHolderAwareRequestFilter.class);
|
||||
servApiFilter.getPropertyValues().add("authenticationManager", authenticationManager);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -577,10 +552,6 @@ class HttpConfigurationBuilder {
|
||||
filters.add(new OrderDecorator(concurrentSessionFilter, CONCURRENT_SESSION_FILTER));
|
||||
}
|
||||
|
||||
if (webAsyncManagerFilter != null) {
|
||||
filters.add(new OrderDecorator(webAsyncManagerFilter, WEB_ASYNC_MANAGER_FILTER));
|
||||
}
|
||||
|
||||
filters.add(new OrderDecorator(securityContextPersistenceFilter, SECURITY_CONTEXT_FILTER));
|
||||
|
||||
if (servApiFilter != null) {
|
||||
|
||||
-1
@@ -140,7 +140,6 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
|
||||
httpBldr.getSessionStrategy(), portMapper, portResolver);
|
||||
|
||||
httpBldr.setLogoutHandlers(authBldr.getLogoutHandlers());
|
||||
httpBldr.setEntryPoint(authBldr.getEntryPointBean());
|
||||
|
||||
authenticationProviders.addAll(authBldr.getProviders());
|
||||
|
||||
|
||||
@@ -1,25 +1,10 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.config.http;
|
||||
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Stores the default order numbers of all Spring Security filters for use in configuration.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
*/
|
||||
|
||||
enum SecurityFilters {
|
||||
@@ -27,8 +12,6 @@ enum SecurityFilters {
|
||||
CHANNEL_FILTER,
|
||||
SECURITY_CONTEXT_FILTER,
|
||||
CONCURRENT_SESSION_FILTER,
|
||||
/** {@link WebAsyncManagerIntegrationFilter} */
|
||||
WEB_ASYNC_MANAGER_FILTER,
|
||||
LOGOUT_FILTER,
|
||||
X509_FILTER,
|
||||
PRE_AUTH_FILTER,
|
||||
|
||||
+19
-4
@@ -1,3 +1,18 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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.config.method;
|
||||
|
||||
import static org.springframework.security.config.Elements.*;
|
||||
@@ -47,7 +62,6 @@ import org.springframework.security.access.vote.AffirmativeBased;
|
||||
import org.springframework.security.access.vote.AuthenticatedVoter;
|
||||
import org.springframework.security.access.vote.RoleVoter;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.config.BeanIds;
|
||||
import org.springframework.security.config.Elements;
|
||||
import org.springframework.security.config.authentication.AuthenticationManagerFactoryBean;
|
||||
@@ -63,6 +77,7 @@ import org.w3c.dom.Element;
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @since 2.0
|
||||
*/
|
||||
public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionParser {
|
||||
@@ -234,7 +249,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
* expression voter if expression-based access control is enabled.
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private String registerAccessManager(ParserContext pc, boolean jsr250Enabled, BeanDefinition expressionVoter) {
|
||||
|
||||
BeanDefinitionBuilder accessMgrBuilder = BeanDefinitionBuilder.rootBeanDefinition(AffirmativeBased.class);
|
||||
@@ -259,7 +274,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
return id;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings("rawtypes")
|
||||
private BeanReference registerDelegatingMethodSecurityMetadataSource(ParserContext pc, ManagedList delegates, Object source) {
|
||||
RootBeanDefinition delegatingMethodSecurityMetadataSource = new RootBeanDefinition(DelegatingMethodSecurityMetadataSource.class);
|
||||
delegatingMethodSecurityMetadataSource.setSource(source);
|
||||
@@ -383,7 +398,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
if (delegate == null) {
|
||||
Assert.state(beanFactory != null, "BeanFactory must be set to resolve " + authMgrBean);
|
||||
try {
|
||||
delegate = beanFactory.getBean(authMgrBean, ProviderManager.class);
|
||||
delegate = beanFactory.getBean(authMgrBean, AuthenticationManager.class);
|
||||
} catch (NoSuchBeanDefinitionException e) {
|
||||
if (BeanIds.AUTHENTICATION_MANAGER.equals(e.getBeanName())) {
|
||||
throw new NoSuchBeanDefinitionException(BeanIds.AUTHENTICATION_MANAGER,
|
||||
|
||||
+18
-27
@@ -51,7 +51,6 @@ final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||
private final PointcutParser parser;
|
||||
private final Set<String> processedBeans = new HashSet<String>();
|
||||
|
||||
|
||||
public ProtectPointcutPostProcessor(MapBasedMethodSecurityMetadataSource mapBasedMethodSecurityMetadataSource) {
|
||||
Assert.notNull(mapBasedMethodSecurityMetadataSource, "MapBasedMethodSecurityMetadataSource to populate is required");
|
||||
this.mapBasedMethodSecurityMetadataSource = mapBasedMethodSecurityMetadataSource;
|
||||
@@ -81,34 +80,26 @@ final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||
return bean;
|
||||
}
|
||||
|
||||
synchronized(processedBeans) {
|
||||
// check again synchronized this time
|
||||
if (processedBeans.contains(beanName)) {
|
||||
return bean;
|
||||
}
|
||||
|
||||
// Obtain methods for the present bean
|
||||
Method[] methods;
|
||||
try {
|
||||
methods = bean.getClass().getMethods();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e.getMessage());
|
||||
}
|
||||
|
||||
// Check to see if any of those methods are compatible with our pointcut expressions
|
||||
for (Method method : methods) {
|
||||
for (PointcutExpression expression : pointCutExpressions) {
|
||||
// Try for the bean class directly
|
||||
if (attemptMatch(bean.getClass(), method, expression, beanName)) {
|
||||
// We've found the first expression that matches this method, so move onto the next method now
|
||||
break; // the "while" loop, not the "for" loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
processedBeans.add(beanName);
|
||||
// Obtain methods for the present bean
|
||||
Method[] methods;
|
||||
try {
|
||||
methods = bean.getClass().getMethods();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e.getMessage());
|
||||
}
|
||||
|
||||
// Check to see if any of those methods are compatible with our pointcut expressions
|
||||
for (Method method : methods) {
|
||||
for (PointcutExpression expression : pointCutExpressions) {
|
||||
// Try for the bean class directly
|
||||
if (attemptMatch(bean.getClass(), method, expression, beanName)) {
|
||||
// We've found the first expression that matches this method, so move onto the next method now
|
||||
break; // the "while" loop, not the "for" loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
processedBeans.add(beanName);
|
||||
|
||||
return bean;
|
||||
}
|
||||
|
||||
+1
-18
@@ -1,15 +1,3 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.config.http
|
||||
|
||||
import javax.servlet.Filter
|
||||
@@ -20,13 +8,8 @@ import org.springframework.security.config.AbstractXmlConfigTests
|
||||
import org.springframework.security.config.BeanIds
|
||||
import org.springframework.security.web.FilterInvocation
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
abstract class AbstractHttpConfigTests extends AbstractXmlConfigTests {
|
||||
final int AUTO_CONFIG_FILTERS = 12;
|
||||
final int AUTO_CONFIG_FILTERS = 11;
|
||||
|
||||
def httpAutoConfig(Closure c) {
|
||||
xml.http('auto-config': 'true', c)
|
||||
|
||||
+3
-6
@@ -54,7 +54,6 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationEn
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
|
||||
import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
|
||||
@@ -80,7 +79,6 @@ import org.springframework.security.authentication.AuthenticationManager
|
||||
* @author Rob Winch
|
||||
*/
|
||||
class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
def 'Minimal configuration parses'() {
|
||||
setup:
|
||||
xml.http {
|
||||
@@ -103,7 +101,6 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
Iterator<Filter> filters = filterList.iterator();
|
||||
|
||||
assert filters.next() instanceof SecurityContextPersistenceFilter
|
||||
assert filters.next() instanceof WebAsyncManagerIntegrationFilter
|
||||
assert filters.next() instanceof LogoutFilter
|
||||
Object authProcFilter = filters.next();
|
||||
assert authProcFilter instanceof UsernamePasswordAuthenticationFilter
|
||||
@@ -184,7 +181,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
createAppContext()
|
||||
|
||||
expect:
|
||||
getFilters("/anything")[6] instanceof AnonymousAuthenticationFilter
|
||||
getFilters("/anything")[5] instanceof AnonymousAuthenticationFilter
|
||||
}
|
||||
|
||||
def anonymousFilterIsRemovedIfDisabledFlagSet() {
|
||||
@@ -357,7 +354,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
AUTO_CONFIG_FILTERS + 3 == filters.size();
|
||||
filters[0] instanceof SecurityContextHolderAwareRequestFilter
|
||||
filters[1] instanceof SecurityContextPersistenceFilter
|
||||
filters[5] instanceof SecurityContextHolderAwareRequestFilter
|
||||
filters[4] instanceof SecurityContextHolderAwareRequestFilter
|
||||
filters[1] instanceof SecurityContextPersistenceFilter
|
||||
}
|
||||
|
||||
@@ -380,7 +377,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
createAppContext()
|
||||
|
||||
expect:
|
||||
getFilters("/someurl")[3] instanceof X509AuthenticationFilter
|
||||
getFilters("/someurl")[2] instanceof X509AuthenticationFilter
|
||||
}
|
||||
|
||||
def x509SubjectPrincipalRegexCanBeSetUsingPropertyPlaceholder() {
|
||||
|
||||
-142
@@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.config.http
|
||||
|
||||
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML
|
||||
|
||||
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
|
||||
import org.springframework.security.TestDataSource
|
||||
import org.springframework.security.authentication.ProviderManager
|
||||
import org.springframework.security.authentication.RememberMeAuthenticationProvider
|
||||
import org.springframework.security.config.ldap.ContextSourceSettingPostProcessor;
|
||||
import org.springframework.security.core.userdetails.MockUserDetailsService
|
||||
import org.springframework.security.util.FieldUtils
|
||||
import org.springframework.security.web.access.ExceptionTranslationFilter
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
||||
import org.springframework.security.web.authentication.logout.LogoutFilter
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler
|
||||
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl
|
||||
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter
|
||||
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
class SecurityContextHolderAwareRequestConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
def withAutoConfig() {
|
||||
httpAutoConfig () {
|
||||
|
||||
}
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
|
||||
|
||||
expect:
|
||||
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
|
||||
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
|
||||
securityContextAwareFilter.logoutHandlers.size() == 1
|
||||
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
|
||||
}
|
||||
|
||||
def explicitEntryPoint() {
|
||||
xml.http() {
|
||||
'http-basic'('entry-point-ref': 'ep')
|
||||
}
|
||||
bean('ep', BasicAuthenticationEntryPoint.class.name, ['realmName':'whocares'],[:])
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
|
||||
|
||||
expect:
|
||||
securityContextAwareFilter.authenticationEntryPoint == getFilter(ExceptionTranslationFilter).authenticationEntryPoint
|
||||
securityContextAwareFilter.authenticationManager == getFilter(BasicAuthenticationFilter).authenticationManager
|
||||
securityContextAwareFilter.logoutHandlers == null
|
||||
}
|
||||
|
||||
def formLogin() {
|
||||
xml.http() {
|
||||
'form-login'()
|
||||
}
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
|
||||
|
||||
expect:
|
||||
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
|
||||
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
|
||||
securityContextAwareFilter.logoutHandlers == null
|
||||
}
|
||||
|
||||
def multiHttp() {
|
||||
xml.http('authentication-manager-ref' : 'authManager', 'pattern' : '/first/**') {
|
||||
'form-login'('login-page' : '/login')
|
||||
'logout'('invalidate-session' : 'true')
|
||||
}
|
||||
xml.http('authentication-manager-ref' : 'authManager2') {
|
||||
'form-login'('login-page' : '/login2')
|
||||
'logout'('invalidate-session' : 'false')
|
||||
}
|
||||
|
||||
String secondAuthManager = AUTH_PROVIDER_XML.replace("alias='authManager'", "id='authManager2'")
|
||||
createAppContext(AUTH_PROVIDER_XML + secondAuthManager)
|
||||
|
||||
def securityContextAwareFilter = getFilters('/first/filters').find { it instanceof SecurityContextHolderAwareRequestFilter }
|
||||
def secondSecurityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
|
||||
|
||||
expect:
|
||||
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login'
|
||||
securityContextAwareFilter.authenticationManager == getFilters('/first/filters').find { it instanceof UsernamePasswordAuthenticationFilter}.authenticationManager
|
||||
securityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager')
|
||||
securityContextAwareFilter.logoutHandlers.size() == 1
|
||||
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
|
||||
securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == true
|
||||
|
||||
secondSecurityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login2'
|
||||
secondSecurityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
|
||||
secondSecurityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager2')
|
||||
securityContextAwareFilter.logoutHandlers.size() == 1
|
||||
secondSecurityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
|
||||
secondSecurityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
|
||||
}
|
||||
|
||||
def logoutCustom() {
|
||||
xml.http() {
|
||||
'form-login'('login-page' : '/login')
|
||||
'logout'('invalidate-session' : 'false', 'logout-success-url' : '/login?logout', 'delete-cookies' : 'JSESSIONID')
|
||||
}
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
|
||||
|
||||
expect:
|
||||
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
|
||||
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
|
||||
securityContextAwareFilter.logoutHandlers.size() == 2
|
||||
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
|
||||
securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
|
||||
securityContextAwareFilter.logoutHandlers[1].class == CookieClearingLogoutHandler
|
||||
securityContextAwareFilter.logoutHandlers[1].cookiesToClear == ['JSESSIONID']
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -305,7 +305,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
'session-management'('session-fixation-protection': 'none', 'invalid-session-url': '/timeoutUrl')
|
||||
}
|
||||
createAppContext()
|
||||
def filter = getFilters("/someurl")[9]
|
||||
def filter = getFilters("/someurl")[8]
|
||||
|
||||
expect:
|
||||
filter instanceof SessionManagementFilter
|
||||
|
||||
+50
@@ -10,9 +10,11 @@ import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.aop.Advisor;
|
||||
import org.springframework.aop.framework.Advised;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.support.AbstractXmlApplicationContext;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
@@ -29,11 +31,13 @@ import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter;
|
||||
import org.springframework.security.access.vote.AffirmativeBased;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.ConfigTestUtils;
|
||||
import org.springframework.security.config.PostProcessedMockUserDetailsService;
|
||||
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
@@ -368,6 +372,52 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
foo.foo(new SecurityConfig("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsCustomAuthenticationManager() throws Exception {
|
||||
setContext(
|
||||
"<b:bean id='target' class='" + ConcreteFoo.class.getName() + "'/>" +
|
||||
"<method-security-metadata-source id='mds'>" +
|
||||
" <protect method='"+ Foo.class.getName() + ".foo' access='ROLE_ADMIN'/>" +
|
||||
"</method-security-metadata-source>" +
|
||||
"<global-method-security pre-post-annotations='enabled' metadata-source-ref='mds' authentication-manager-ref='customAuthMgr'/>" +
|
||||
"<b:bean id='customAuthMgr' class='org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParserTests$CustomAuthManager'>" +
|
||||
" <b:constructor-arg value='authManager'/>" +
|
||||
"</b:bean>" +
|
||||
AUTH_PROVIDER_XML
|
||||
);
|
||||
SecurityContextHolder.getContext().setAuthentication(bob);
|
||||
Foo foo = (Foo) appContext.getBean("target");
|
||||
try {
|
||||
foo.foo(new SecurityConfig("A"));
|
||||
fail("Bob can't invoke admin methods");
|
||||
} catch (AccessDeniedException expected) {
|
||||
}
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
|
||||
foo.foo(new SecurityConfig("A"));
|
||||
}
|
||||
|
||||
static class CustomAuthManager implements AuthenticationManager, ApplicationContextAware {
|
||||
private String beanName;
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
CustomAuthManager(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public Authentication authenticate(Authentication authentication)
|
||||
throws AuthenticationException {
|
||||
return authenticationManager.authenticate(authentication);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
|
||||
*/
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
this.authenticationManager = applicationContext.getBean(beanName,AuthenticationManager.class);
|
||||
}
|
||||
}
|
||||
|
||||
private void setContext(String context) {
|
||||
appContext = new InMemoryXmlApplicationContext(context);
|
||||
}
|
||||
|
||||
+1
-2
@@ -19,8 +19,7 @@ dependencies {
|
||||
|
||||
testCompile 'commons-collections:commons-collections:3.2',
|
||||
"org.springframework:spring-test:$springVersion",
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
powerMockDependencies
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion"
|
||||
|
||||
testRuntime "hsqldb:hsqldb:$hsqlVersion",
|
||||
"cglib:cglib-nodep:$cglibVersion"
|
||||
|
||||
+5
@@ -20,7 +20,12 @@ package org.springframework.security.authentication.encoding;
|
||||
* Interface for performing authentication operations on a password.
|
||||
*
|
||||
* @author colin sampaleanu
|
||||
* @deprecated It is recommended to use
|
||||
* {@link org.springframework.security.crypto.password.PasswordEncoder}
|
||||
* instead which better accommodates best practice of randomly
|
||||
* generated salt that is included with the password.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface PasswordEncoder {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* An internal support class that wraps {@link Callable} with {@link DelegatingSecurityContextCallable} and
|
||||
* {@link Runnable} with {@link DelegatingSecurityContextRunnable}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
abstract class AbstractDelegatingSecurityContextSupport {
|
||||
|
||||
private final SecurityContext securityContext;
|
||||
|
||||
/**
|
||||
* Creates a new {@link AbstractDelegatingSecurityContextSupport} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} and
|
||||
* each {@link DelegatingSecurityContextCallable} or null to default to the current {@link SecurityContext}.
|
||||
*/
|
||||
AbstractDelegatingSecurityContextSupport(SecurityContext securityContext) {
|
||||
this.securityContext = securityContext;
|
||||
}
|
||||
|
||||
protected final Runnable wrap(Runnable delegate) {
|
||||
return DelegatingSecurityContextRunnable.create(delegate, securityContext);
|
||||
}
|
||||
|
||||
protected final <T> Callable<T> wrap(Callable<T> delegate) {
|
||||
return DelegatingSecurityContextCallable.create(delegate, securityContext);
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Wraps a delegate {@link Callable} with logic for setting up a {@link SecurityContext} before invoking the delegate
|
||||
* {@link Callable} and then removing the {@link SecurityContext} after the delegate has completed.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class DelegatingSecurityContextCallable<V> implements Callable<V> {
|
||||
|
||||
private final Callable<V> delegate;
|
||||
|
||||
private final SecurityContext securityContext;
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextCallable} with a specific {@link SecurityContext}.
|
||||
* @param delegate the delegate {@link DelegatingSecurityContextCallable} to run with the specified
|
||||
* {@link SecurityContext}. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to establish for the delegate {@link Callable}. Cannot be
|
||||
* null.
|
||||
*/
|
||||
public DelegatingSecurityContextCallable(Callable<V> delegate, SecurityContext securityContext) {
|
||||
Assert.notNull(delegate, "delegate cannot be null");
|
||||
Assert.notNull(securityContext, "securityContext cannot be null");
|
||||
this.delegate = delegate;
|
||||
this.securityContext = securityContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextCallable} with the {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder}.
|
||||
* @param delegate the delegate {@link Callable} to run under the current {@link SecurityContext}. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextCallable(Callable<V> delegate) {
|
||||
this(delegate, SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
public V call() throws Exception {
|
||||
try {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
return delegate.call();
|
||||
}
|
||||
finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link DelegatingSecurityContextCallable} and with the given {@link Callable} and
|
||||
* {@link SecurityContext}, but if the securityContext is null will defaults to the current {@link SecurityContext}
|
||||
* on the {@link SecurityContextHolder}
|
||||
*
|
||||
* @param delegate the delegate {@link DelegatingSecurityContextCallable} to run with the specified
|
||||
* {@link SecurityContext}. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to establish for the delegate {@link Callable}. If null,
|
||||
* defaults to {@link SecurityContextHolder#getContext()}
|
||||
* @return
|
||||
*/
|
||||
public static <V> Callable<V> create(Callable<V> delegate, SecurityContext securityContext) {
|
||||
return securityContext == null ? new DelegatingSecurityContextCallable<V>(delegate)
|
||||
: new DelegatingSecurityContextCallable<V>(delegate, securityContext);
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* An {@link Executor} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class DelegatingSecurityContextExecutor extends AbstractDelegatingSecurityContextSupport implements Executor {
|
||||
private final Executor delegate;
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextExecutor} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateExecutor the {@link Executor} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} or
|
||||
* null to default to the current {@link SecurityContext}
|
||||
*/
|
||||
public DelegatingSecurityContextExecutor(Executor delegateExecutor, SecurityContext securityContext) {
|
||||
super(securityContext);
|
||||
Assert.notNull(delegateExecutor, "delegateExecutor cannot be null");
|
||||
this.delegate = delegateExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextExecutor} that uses the current {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder} at the time the task is submitted.
|
||||
*
|
||||
* @param delegate the {@link Executor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextExecutor(Executor delegate) {
|
||||
this(delegate, null);
|
||||
}
|
||||
|
||||
public final void execute(Runnable task) {
|
||||
task = wrap(task);
|
||||
delegate.execute(task);
|
||||
}
|
||||
|
||||
protected final Executor getDelegateExecutor() {
|
||||
return delegate;
|
||||
}
|
||||
}
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* An {@link ExecutorService} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable} and each
|
||||
* {@link Callable} in a {@link DelegatingSecurityContextCallable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class DelegatingSecurityContextExecutorService extends DelegatingSecurityContextExecutor implements
|
||||
ExecutorService {
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextExecutorService} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateExecutorService the {@link ExecutorService} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} and
|
||||
* each {@link DelegatingSecurityContextCallable}.
|
||||
*/
|
||||
public DelegatingSecurityContextExecutorService(ExecutorService delegateExecutorService,
|
||||
SecurityContext securityContext) {
|
||||
super(delegateExecutorService, securityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextExecutorService} that uses the current {@link SecurityContext} from
|
||||
* the {@link SecurityContextHolder}.
|
||||
*
|
||||
* @param delegateTaskExecutor the {@link TaskExecutor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextExecutorService(ExecutorService delegate) {
|
||||
this(delegate, null);
|
||||
}
|
||||
|
||||
public final void shutdown() {
|
||||
getDelegate().shutdown();
|
||||
}
|
||||
|
||||
public final List<Runnable> shutdownNow() {
|
||||
return getDelegate().shutdownNow();
|
||||
}
|
||||
|
||||
public final boolean isShutdown() {
|
||||
return getDelegate().isShutdown();
|
||||
}
|
||||
|
||||
public final boolean isTerminated() {
|
||||
return getDelegate().isTerminated();
|
||||
}
|
||||
|
||||
public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return getDelegate().awaitTermination(timeout, unit);
|
||||
}
|
||||
|
||||
public final <T> Future<T> submit(Callable<T> task) {
|
||||
task = wrap(task);
|
||||
return getDelegate().submit(task);
|
||||
}
|
||||
|
||||
public final <T> Future<T> submit(Runnable task, T result) {
|
||||
task = wrap(task);
|
||||
return getDelegate().submit(task, result);
|
||||
}
|
||||
|
||||
public final Future<?> submit(Runnable task) {
|
||||
task = wrap(task);
|
||||
return getDelegate().submit(task);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public final List invokeAll(Collection tasks) throws InterruptedException {
|
||||
tasks = createTasks(tasks);
|
||||
return getDelegate().invokeAll(tasks);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public final List invokeAll(Collection tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
tasks = createTasks(tasks);
|
||||
return getDelegate().invokeAll(tasks, timeout, unit);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public final Object invokeAny(Collection tasks) throws InterruptedException, ExecutionException {
|
||||
tasks = createTasks(tasks);
|
||||
return getDelegate().invokeAny(tasks);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public final Object invokeAny(Collection tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException, ExecutionException, TimeoutException {
|
||||
tasks = createTasks(tasks);
|
||||
return getDelegate().invokeAny(tasks, timeout, unit);
|
||||
}
|
||||
|
||||
private <T> Collection<Callable<T>> createTasks(Collection<Callable<T>> tasks) {
|
||||
if (tasks == null) {
|
||||
return null;
|
||||
}
|
||||
List<Callable<T>> results = new ArrayList<Callable<T>>(tasks.size());
|
||||
for (Callable<T> task : tasks) {
|
||||
results.add(wrap(task));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private ExecutorService getDelegate() {
|
||||
return (ExecutorService) getDelegateExecutor();
|
||||
}
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Wraps a delegate {@link Runnable} with logic for setting up a {@link SecurityContext} before invoking the delegate
|
||||
* {@link Runnable} and then removing the {@link SecurityContext} after the delegate has completed.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class DelegatingSecurityContextRunnable implements Runnable {
|
||||
|
||||
private final Runnable delegate;
|
||||
|
||||
private final SecurityContext securityContext;
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextRunnable} with a specific {@link SecurityContext}.
|
||||
* @param delegate the delegate {@link Runnable} to run with the specified {@link SecurityContext}. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to establish for the delegate {@link Runnable}. Cannot be
|
||||
* null.
|
||||
*/
|
||||
public DelegatingSecurityContextRunnable(Runnable delegate, SecurityContext securityContext) {
|
||||
Assert.notNull(delegate, "delegate cannot be null");
|
||||
Assert.notNull(securityContext, "securityContext cannot be null");
|
||||
this.delegate = delegate;
|
||||
this.securityContext = securityContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextRunnable} with the {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder}.
|
||||
* @param delegate the delegate {@link Runnable} to run under the current {@link SecurityContext}. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextRunnable(Runnable delegate) {
|
||||
this(delegate, SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
delegate.run();
|
||||
}
|
||||
finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method for creating a {@link DelegatingSecurityContextRunnable}.
|
||||
*
|
||||
* @param delegate the original {@link Runnable} that will be delegated to after establishing a
|
||||
* {@link SecurityContext} on the {@link SecurityContextHolder}. Cannot have null.
|
||||
* @param securityContext the {@link SecurityContext} to establish before invoking the delegate {@link Runnable}. If
|
||||
* null, the current {@link SecurityContext} from the {@link SecurityContextHolder} will be used.
|
||||
* @return
|
||||
*/
|
||||
public static Runnable create(Runnable delegate, SecurityContext securityContext) {
|
||||
Assert.notNull(delegate, "delegate cannot be null");
|
||||
return securityContext == null ? new DelegatingSecurityContextRunnable(delegate)
|
||||
: new DelegatingSecurityContextRunnable(delegate, securityContext);
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* An {@link ScheduledExecutorService} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable}
|
||||
* and each {@link Callable} in a {@link DelegatingSecurityContextCallable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class DelegatingSecurityContextScheduledExecutorService extends DelegatingSecurityContextExecutorService
|
||||
implements ScheduledExecutorService {
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses the specified
|
||||
* {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateScheduledExecutorService the {@link ScheduledExecutorService} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} and
|
||||
* each {@link DelegatingSecurityContextCallable}.
|
||||
*/
|
||||
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegateScheduledExecutorService,
|
||||
SecurityContext securityContext) {
|
||||
super(delegateScheduledExecutorService, securityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses the current
|
||||
* {@link SecurityContext} from the {@link SecurityContextHolder}.
|
||||
*
|
||||
* @param delegateTaskExecutor the {@link TaskExecutor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegate) {
|
||||
this(delegate, null);
|
||||
}
|
||||
|
||||
public final ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
|
||||
command = wrap(command);
|
||||
return getDelegate().schedule(command, delay, unit);
|
||||
}
|
||||
|
||||
public final <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
|
||||
callable = wrap(callable);
|
||||
return getDelegate().schedule(callable, delay, unit);
|
||||
}
|
||||
|
||||
public final ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
|
||||
command = wrap(command);
|
||||
return getDelegate().scheduleAtFixedRate(command, initialDelay, period, unit);
|
||||
}
|
||||
|
||||
public final ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
|
||||
TimeUnit unit) {
|
||||
command = wrap(command);
|
||||
return getDelegate().scheduleWithFixedDelay(command, initialDelay, delay, unit);
|
||||
}
|
||||
|
||||
private ScheduledExecutorService getDelegate() {
|
||||
return (ScheduledExecutorService) getDelegateExecutor();
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,11 @@ public class SpringSecurityCoreVersion {
|
||||
* N.B. Classes are not intended to be serializable between different versions.
|
||||
* See SEC-1709 for why we still need a serial version.
|
||||
*/
|
||||
public static final long SERIAL_VERSION_UID = 320L;
|
||||
public static final long SERIAL_VERSION_UID = 310L;
|
||||
|
||||
static final String SPRING_MAJOR_VERSION = "3";
|
||||
|
||||
static final String MIN_SPRING_VERSION = "3.2.0.BUILD-SNAPSHOT";
|
||||
static final String MIN_SPRING_VERSION = "3.0.7.RELEASE";
|
||||
|
||||
static {
|
||||
// Check Spring Compatibility
|
||||
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.scheduling;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.core.task.AsyncTaskExecutor;
|
||||
import org.springframework.scheduling.SchedulingTaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
|
||||
|
||||
/**
|
||||
* An {@link SchedulingTaskExecutor} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable} and each
|
||||
* {@link Callable} in a {@link DelegatingSecurityContextCallable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class DelegatingSecurityContextSchedulingTaskExecutor extends DelegatingSecurityContextAsyncTaskExecutor
|
||||
implements SchedulingTaskExecutor {
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextSchedulingTaskExecutor} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateSchedulingTaskExecutor the {@link SchedulingTaskExecutor} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} and
|
||||
* {@link DelegatingSecurityContextCallable}
|
||||
*/
|
||||
public DelegatingSecurityContextSchedulingTaskExecutor(SchedulingTaskExecutor delegateSchedulingTaskExecutor,
|
||||
SecurityContext securityContext) {
|
||||
super(delegateSchedulingTaskExecutor, securityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextSchedulingTaskExecutor} that uses the current {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextSchedulingTaskExecutor(SchedulingTaskExecutor delegateAsyncTaskExecutor) {
|
||||
this(delegateAsyncTaskExecutor, null);
|
||||
}
|
||||
|
||||
public boolean prefersShortLivedTasks() {
|
||||
return getDelegate().prefersShortLivedTasks();
|
||||
}
|
||||
|
||||
private SchedulingTaskExecutor getDelegate() {
|
||||
return (SchedulingTaskExecutor) getDelegateExecutor();
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.task;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.springframework.core.task.AsyncTaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* An {@link AsyncTaskExecutor} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable} and each
|
||||
* {@link Callable} in a {@link DelegatingSecurityContextCallable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class DelegatingSecurityContextAsyncTaskExecutor extends DelegatingSecurityContextTaskExecutor implements
|
||||
AsyncTaskExecutor {
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextAsyncTaskExecutor} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable} and
|
||||
* {@link DelegatingSecurityContextCallable}
|
||||
*/
|
||||
public DelegatingSecurityContextAsyncTaskExecutor(AsyncTaskExecutor delegateAsyncTaskExecutor,
|
||||
SecurityContext securityContext) {
|
||||
super(delegateAsyncTaskExecutor, securityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextAsyncTaskExecutor} that uses the current {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextAsyncTaskExecutor(AsyncTaskExecutor delegateAsyncTaskExecutor) {
|
||||
this(delegateAsyncTaskExecutor, null);
|
||||
}
|
||||
|
||||
public final void execute(Runnable task, long startTimeout) {
|
||||
task = wrap(task);
|
||||
getDelegate().execute(task, startTimeout);
|
||||
}
|
||||
|
||||
public final Future<?> submit(Runnable task) {
|
||||
task = wrap(task);
|
||||
return getDelegate().submit(task);
|
||||
}
|
||||
|
||||
public final <T> Future<T> submit(Callable<T> task) {
|
||||
task = wrap(task);
|
||||
return getDelegate().submit(task);
|
||||
}
|
||||
|
||||
private AsyncTaskExecutor getDelegate() {
|
||||
return (AsyncTaskExecutor) getDelegateExecutor();
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.task;
|
||||
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* An {@link TaskExecutor} which wraps each {@link Runnable} in a {@link DelegatingSecurityContextRunnable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class DelegatingSecurityContextTaskExecutor extends DelegatingSecurityContextExecutor implements TaskExecutor {
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextTaskExecutor} that uses the specified {@link SecurityContext}.
|
||||
*
|
||||
* @param delegateTaskExecutor the {@link TaskExecutor} to delegate to. Cannot be null.
|
||||
* @param securityContext the {@link SecurityContext} to use for each {@link DelegatingSecurityContextRunnable}
|
||||
*/
|
||||
public DelegatingSecurityContextTaskExecutor(TaskExecutor delegateTaskExecutor, SecurityContext securityContext) {
|
||||
super(delegateTaskExecutor, securityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link DelegatingSecurityContextTaskExecutor} that uses the current {@link SecurityContext} from
|
||||
* the {@link SecurityContextHolder}.
|
||||
*
|
||||
* @param delegateTaskExecutor the {@link TaskExecutor} to delegate to. Cannot be null.
|
||||
*/
|
||||
public DelegatingSecurityContextTaskExecutor(TaskExecutor delegate) {
|
||||
this(delegate, null);
|
||||
}
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
|
||||
|
||||
/**
|
||||
* Abstract class for testing {@link DelegatingSecurityContextExecutorService} which allows customization of
|
||||
* how {@link DelegatingSecurityContextExecutorService} and its mocks are created.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see CurrentDelegatingSecurityContextExecutorServiceTests
|
||||
* @see ExplicitDelegatingSecurityContextExecutorServiceTests
|
||||
*/
|
||||
public abstract class AbstractDelegatingSecurityContextExecutorServiceTests extends AbstractDelegatingSecurityContextExecutorTests {
|
||||
@Mock
|
||||
private Future<Object> expectedFutureObject;
|
||||
@Mock
|
||||
private Object resultArg;
|
||||
|
||||
protected DelegatingSecurityContextExecutorService executor;
|
||||
|
||||
@Before
|
||||
public final void setUpExecutorService() {
|
||||
executor = create();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingSecurityContextExecutorService(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shutdown() {
|
||||
executor.shutdown();
|
||||
verify(delegate).shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shutdownNow() {
|
||||
List<Runnable> result = executor.shutdownNow();
|
||||
verify(delegate).shutdownNow();
|
||||
assertThat(result).isEqualTo(delegate.shutdownNow()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isShutdown() {
|
||||
boolean result = executor.isShutdown();
|
||||
verify(delegate).isShutdown();
|
||||
assertThat(result).isEqualTo(delegate.isShutdown()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isTerminated() {
|
||||
boolean result = executor.isTerminated();
|
||||
verify(delegate).isTerminated();
|
||||
assertThat(result).isEqualTo(delegate.isTerminated()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void awaitTermination() throws InterruptedException {
|
||||
boolean result = executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
verify(delegate).awaitTermination(1, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(delegate.awaitTermination(1, TimeUnit.SECONDS)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void submitCallable() throws Exception {
|
||||
when(delegate.submit(wrappedCallable)).thenReturn(expectedFutureObject);
|
||||
Future<Object> result = executor.submit(callable);
|
||||
verify(delegate).submit(wrappedCallable);
|
||||
assertThat(result).isEqualTo(expectedFutureObject);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void submitRunnableWithResult() throws Exception {
|
||||
when(delegate.submit(wrappedRunnable, resultArg)).thenReturn(expectedFutureObject);
|
||||
Future<Object> result = executor.submit(runnable, resultArg);
|
||||
verify(delegate).submit(wrappedRunnable, resultArg);
|
||||
assertThat(result).isEqualTo(expectedFutureObject);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void submitRunnable() throws Exception {
|
||||
when((Future<Object>)delegate.submit(wrappedRunnable)).thenReturn(expectedFutureObject);
|
||||
Future<?> result = executor.submit(runnable);
|
||||
verify(delegate).submit(wrappedRunnable);
|
||||
assertThat(result).isEqualTo(expectedFutureObject);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void invokeAll() throws Exception {
|
||||
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
|
||||
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
|
||||
when(delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult);
|
||||
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable));
|
||||
verify(delegate).invokeAll(wrappedCallables);
|
||||
assertThat(result).isEqualTo(exectedResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void invokeAllTimeout() throws Exception {
|
||||
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
|
||||
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
|
||||
when(delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
|
||||
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable), 1, TimeUnit.SECONDS);
|
||||
verify(delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(exectedResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void invokeAny() throws Exception {
|
||||
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
|
||||
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
|
||||
when(delegate.invokeAny(wrappedCallables)).thenReturn(exectedResult);
|
||||
Object result = executor.invokeAny(Arrays.asList(callable));
|
||||
verify(delegate).invokeAny(wrappedCallables);
|
||||
assertThat(result).isEqualTo(exectedResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void invokeAnyTimeout() throws Exception {
|
||||
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
|
||||
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
|
||||
when(delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
|
||||
Object result = executor.invokeAny(Arrays.asList(callable), 1, TimeUnit.SECONDS);
|
||||
verify(delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(exectedResult);
|
||||
}
|
||||
|
||||
protected abstract DelegatingSecurityContextExecutorService create();
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
|
||||
/**
|
||||
* Abstract class for testing {@link DelegatingSecurityContextExecutor} which allows customization of
|
||||
* how {@link DelegatingSecurityContextExecutor} and its mocks are created.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see CurrentDelegatingSecurityContextExecutorTests
|
||||
* @see ExplicitDelegatingSecurityContextExecutorTests
|
||||
*/
|
||||
public abstract class AbstractDelegatingSecurityContextExecutorTests extends AbstractDelegatingSecurityContextTestSupport {
|
||||
@Mock
|
||||
protected ScheduledExecutorService delegate;
|
||||
|
||||
private DelegatingSecurityContextExecutor executor;
|
||||
|
||||
// --- constructor ---
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingSecurityContextExecutor(null);
|
||||
}
|
||||
|
||||
// --- execute ---
|
||||
|
||||
@Test
|
||||
public void execute() {
|
||||
executor = create();
|
||||
executor.execute(runnable);
|
||||
verify(getExecutor()).execute(wrappedRunnable);
|
||||
}
|
||||
|
||||
protected Executor getExecutor() {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
protected abstract DelegatingSecurityContextExecutor create();
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
|
||||
/**
|
||||
* Abstract class for testing {@link DelegatingSecurityContextScheduledExecutorService} which allows customization of
|
||||
* how {@link DelegatingSecurityContextScheduledExecutorService} and its mocks are created.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see CurrentDelegatingSecurityContextScheduledExecutorServiceTests
|
||||
* @see ExplicitDelegatingSecurityContextScheduledExecutorServiceTests
|
||||
*/
|
||||
public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceTests extends
|
||||
AbstractDelegatingSecurityContextExecutorServiceTests {
|
||||
@Mock
|
||||
private ScheduledFuture<Object> expectedResult;
|
||||
|
||||
private DelegatingSecurityContextScheduledExecutorService executor;
|
||||
|
||||
@Before
|
||||
public final void setUpExecutor() {
|
||||
executor = create();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void scheduleRunnable() {
|
||||
when((ScheduledFuture<Object>)delegate.schedule(wrappedRunnable, 1, TimeUnit.SECONDS)).thenReturn(expectedResult);
|
||||
ScheduledFuture<?> result = executor.schedule(runnable, 1, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(expectedResult);
|
||||
verify(delegate).schedule(wrappedRunnable, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void scheduleCallable() {
|
||||
when((ScheduledFuture<Object>)delegate.schedule(wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(expectedResult);
|
||||
ScheduledFuture<Object> result = executor.schedule(callable, 1, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(expectedResult);
|
||||
verify(delegate).schedule(wrappedCallable, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void scheduleAtFixedRate() {
|
||||
when((ScheduledFuture<Object>)delegate.scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS)).thenReturn(expectedResult);
|
||||
ScheduledFuture<?> result = executor.scheduleAtFixedRate(runnable, 1, 2, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(expectedResult);
|
||||
verify(delegate).scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void scheduleWithFixedDelay() {
|
||||
when((ScheduledFuture<Object>)delegate.scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS)).thenReturn(expectedResult);
|
||||
ScheduledFuture<?> result = executor.scheduleWithFixedDelay(runnable, 1, 2, TimeUnit.SECONDS);
|
||||
assertThat(result).isEqualTo(expectedResult);
|
||||
verify(delegate).scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected abstract DelegatingSecurityContextScheduledExecutorService create();
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.powermock.api.mockito.PowerMockito.doReturn;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* Abstract base class for testing classes that extend {@link AbstractDelegatingSecurityContextSupport}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ DelegatingSecurityContextRunnable.class, DelegatingSecurityContextCallable.class })
|
||||
public abstract class AbstractDelegatingSecurityContextTestSupport {
|
||||
@Mock
|
||||
protected SecurityContext securityContext;
|
||||
|
||||
@Mock
|
||||
protected SecurityContext currentSecurityContext;
|
||||
|
||||
@Captor
|
||||
protected ArgumentCaptor<SecurityContext> securityContextCaptor;
|
||||
|
||||
@Mock
|
||||
protected Callable<Object> callable;
|
||||
|
||||
@Mock
|
||||
protected Callable<Object> wrappedCallable;
|
||||
|
||||
@Mock
|
||||
protected Runnable runnable;
|
||||
|
||||
@Mock
|
||||
protected Runnable wrappedRunnable;
|
||||
|
||||
public final void explicitSecurityContextPowermockSetup() throws Exception {
|
||||
spy(DelegatingSecurityContextCallable.class);
|
||||
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", eq(callable),
|
||||
securityContextCaptor.capture());
|
||||
spy(DelegatingSecurityContextRunnable.class);
|
||||
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", eq(runnable),
|
||||
securityContextCaptor.capture());
|
||||
}
|
||||
|
||||
public final void currentSecurityContextPowermockSetup() throws Exception {
|
||||
spy(DelegatingSecurityContextCallable.class);
|
||||
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", callable, null);
|
||||
spy(DelegatingSecurityContextRunnable.class);
|
||||
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", runnable, null);
|
||||
}
|
||||
|
||||
@Before
|
||||
public final void setContext() {
|
||||
SecurityContextHolder.setContext(currentSecurityContext);
|
||||
}
|
||||
|
||||
@After
|
||||
public final void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextExecutorService}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentDelegatingSecurityContextExecutorServiceTests extends AbstractDelegatingSecurityContextExecutorServiceTests{
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextExecutorService create() {
|
||||
return new DelegatingSecurityContextExecutorService(delegate);
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentDelegatingSecurityContextExecutorTests extends
|
||||
AbstractDelegatingSecurityContextExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextExecutor create() {
|
||||
return new DelegatingSecurityContextExecutor(getExecutor());
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextScheduledExecutorService}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentDelegatingSecurityContextScheduledExecutorServiceTests extends
|
||||
AbstractDelegatingSecurityContextScheduledExecutorServiceTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
this.currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextScheduledExecutorService create() {
|
||||
return new DelegatingSecurityContextScheduledExecutorService(delegate);
|
||||
}
|
||||
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.internal.stubbing.answers.Returns;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingSecurityContextCallableTests {
|
||||
@Mock
|
||||
private Callable<Object> delegate;
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private Object callableResult;
|
||||
|
||||
private Callable<Object> callable;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("serial")
|
||||
public void setUp() throws Exception {
|
||||
when(delegate.call()).thenAnswer(new Returns(callableResult) {
|
||||
@Override
|
||||
public Object answer(InvocationOnMock invocation) throws Throwable {
|
||||
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
|
||||
return super.answer(invocation);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
// --- constructor ---
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingSecurityContextCallable<Object>(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegateNonNullSecurityContext() {
|
||||
new DelegatingSecurityContextCallable<Object>(null, securityContext);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegateAndSecurityContext() {
|
||||
new DelegatingSecurityContextCallable<Object>(null, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullSecurityContext() {
|
||||
new DelegatingSecurityContextCallable<Object>(delegate, null);
|
||||
}
|
||||
|
||||
// --- call ---
|
||||
|
||||
@Test
|
||||
public void call() throws Exception {
|
||||
callable = new DelegatingSecurityContextCallable<Object>(delegate, securityContext);
|
||||
assertWrapped(callable.call());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultSecurityContext() throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
callable = new DelegatingSecurityContextCallable<Object>(delegate);
|
||||
SecurityContextHolder.clearContext(); // ensure callable is what sets up the SecurityContextHolder
|
||||
assertWrapped(callable.call());
|
||||
}
|
||||
|
||||
// --- create ---
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void createNullDelegate() {
|
||||
DelegatingSecurityContextCallable.create(null, securityContext);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void createNullDelegateAndSecurityContext() {
|
||||
DelegatingSecurityContextRunnable.create(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createNullSecurityContext() throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
callable = DelegatingSecurityContextCallable.create(delegate, null);
|
||||
SecurityContextHolder.clearContext(); // ensure callable is what sets up the SecurityContextHolder
|
||||
assertWrapped(callable.call());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void create() throws Exception {
|
||||
callable = DelegatingSecurityContextCallable.create(delegate, securityContext);
|
||||
assertWrapped(callable.call());
|
||||
}
|
||||
|
||||
private void assertWrapped(Object actualResult) throws Exception {
|
||||
assertThat(actualResult).isEqualTo(callableResult);
|
||||
verify(delegate).call();
|
||||
assertThat(SecurityContextHolder.getContext()).isEqualTo(SecurityContextHolder.createEmptyContext());
|
||||
}
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingSecurityContextRunnableTests {
|
||||
@Mock
|
||||
private Runnable delegate;
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private Object callableResult;
|
||||
|
||||
private Runnable runnable;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock invocation) throws Throwable {
|
||||
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.when(delegate).run();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
// --- constructor ---
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingSecurityContextRunnable(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegateNonNullSecurityContext() {
|
||||
new DelegatingSecurityContextRunnable(null, securityContext);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegateAndSecurityContext() {
|
||||
new DelegatingSecurityContextRunnable(null, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullSecurityContext() {
|
||||
new DelegatingSecurityContextRunnable(delegate, null);
|
||||
}
|
||||
|
||||
// --- run ---
|
||||
|
||||
@Test
|
||||
public void call() throws Exception {
|
||||
runnable = new DelegatingSecurityContextRunnable(delegate, securityContext);
|
||||
runnable.run();
|
||||
assertWrapped();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultSecurityContext() throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
runnable = new DelegatingSecurityContextRunnable(delegate);
|
||||
SecurityContextHolder.clearContext(); // ensure runnable is what sets up the SecurityContextHolder
|
||||
runnable.run();
|
||||
assertWrapped();
|
||||
}
|
||||
|
||||
// --- create ---
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void createNullDelegate() {
|
||||
DelegatingSecurityContextRunnable.create(null, securityContext);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void createNullDelegateAndSecurityContext() {
|
||||
DelegatingSecurityContextRunnable.create(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createNullSecurityContext() {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
runnable = DelegatingSecurityContextRunnable.create(delegate, null);
|
||||
SecurityContextHolder.clearContext(); // ensure runnable is what sets up the SecurityContextHolder
|
||||
runnable.run();
|
||||
assertWrapped();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void create() {
|
||||
runnable = DelegatingSecurityContextRunnable.create(delegate, securityContext);
|
||||
runnable.run();
|
||||
assertWrapped();
|
||||
}
|
||||
|
||||
private void assertWrapped() {
|
||||
verify(delegate).run();
|
||||
assertThat(SecurityContextHolder.getContext()).isEqualTo(SecurityContextHolder.createEmptyContext());
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class DelegatingSecurityContextSupportTests extends AbstractDelegatingSecurityContextTestSupport {
|
||||
private AbstractDelegatingSecurityContextSupport support;
|
||||
|
||||
@Test
|
||||
public void wrapCallable() throws Exception {
|
||||
explicitSecurityContextPowermockSetup();
|
||||
support = new ConcreteDelegatingSecurityContextSupport(securityContext);
|
||||
assertThat(support.wrap(callable)).isSameAs(wrappedCallable);
|
||||
assertThat(securityContextCaptor.getValue()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrapCallableNullSecurityContext() throws Exception {
|
||||
currentSecurityContextPowermockSetup();
|
||||
support = new ConcreteDelegatingSecurityContextSupport(null);
|
||||
assertThat(support.wrap(callable)).isSameAs(wrappedCallable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrapRunnable() throws Exception {
|
||||
explicitSecurityContextPowermockSetup();
|
||||
support = new ConcreteDelegatingSecurityContextSupport(securityContext);
|
||||
assertThat(support.wrap(runnable)).isSameAs(wrappedRunnable);
|
||||
assertThat(securityContextCaptor.getValue()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrapRunnableNullSecurityContext() throws Exception {
|
||||
currentSecurityContextPowermockSetup();
|
||||
support = new ConcreteDelegatingSecurityContextSupport(null);
|
||||
assertThat(support.wrap(runnable)).isSameAs(wrappedRunnable);
|
||||
}
|
||||
|
||||
private static class ConcreteDelegatingSecurityContextSupport extends AbstractDelegatingSecurityContextSupport {
|
||||
public ConcreteDelegatingSecurityContextSupport(SecurityContext securityContext) {
|
||||
super(securityContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
/**
|
||||
* Tests Explicitly specifying the {@link SecurityContext} on {@link DelegatingSecurityContextExecutorService}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitDelegatingSecurityContextExecutorServiceTests extends AbstractDelegatingSecurityContextExecutorServiceTests{
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextExecutorService create() {
|
||||
return new DelegatingSecurityContextExecutorService(delegate,securityContext);
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* Tests Explicitly specifying the {@link SecurityContext} on {@link DelegatingSecurityContextExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitDelegatingSecurityContextExecutorTests extends
|
||||
AbstractDelegatingSecurityContextExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextExecutor create() {
|
||||
return new DelegatingSecurityContextExecutor(getExecutor(), securityContext);
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.concurrent;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* Tests Explicitly specifying the {@link SecurityContext} on {@link DelegatingSecurityContextScheduledExecutorService}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitDelegatingSecurityContextScheduledExecutorServiceTests extends
|
||||
AbstractDelegatingSecurityContextScheduledExecutorServiceTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
this.explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextScheduledExecutorService create() {
|
||||
return new DelegatingSecurityContextScheduledExecutorService(delegate, securityContext);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.core;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public class JavaVersionTests {
|
||||
|
||||
private static final int JDK5_CLASS_VERSION = 49;
|
||||
|
||||
@Test
|
||||
public void authenticationCorrectJdkCompatibility() throws Exception {
|
||||
assertClassVersion(Authentication.class);
|
||||
}
|
||||
|
||||
private void assertClassVersion(Class<?> clazz) throws Exception {
|
||||
String classResourceName = clazz.getName().replaceAll("\\.", "/") + ".class";
|
||||
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(classResourceName);
|
||||
try {
|
||||
DataInputStream data = new DataInputStream(input);
|
||||
data.readInt();
|
||||
data.readShort(); // minor
|
||||
int major = data.readShort();
|
||||
assertThat(major).isEqualTo(JDK5_CLASS_VERSION);
|
||||
} finally {
|
||||
try { input.close(); } catch(Exception e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package org.springframework.security.scheduling;
|
||||
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.scheduling.SchedulingTaskExecutor;
|
||||
import org.springframework.security.task.AbstractDelegatingSecurityContextAsyncTaskExecutorTests;
|
||||
|
||||
/**
|
||||
* Abstract class for testing {@link DelegatingSecurityContextSchedulingTaskExecutor} which allows customization of
|
||||
* how {@link DelegatingSecurityContextSchedulingTaskExecutor} and its mocks are created.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see CurrentSecurityContextSchedulingTaskExecutorTests
|
||||
* @see ExplicitSecurityContextSchedulingTaskExecutorTests
|
||||
*/
|
||||
public abstract class AbstractSecurityContextSchedulingTaskExecutorTests extends
|
||||
AbstractDelegatingSecurityContextAsyncTaskExecutorTests {
|
||||
|
||||
@Mock
|
||||
protected SchedulingTaskExecutor taskExecutorDelegate;
|
||||
|
||||
private DelegatingSecurityContextSchedulingTaskExecutor executor;
|
||||
|
||||
@Test
|
||||
public void prefersShortLivedTasks() {
|
||||
executor = create();
|
||||
executor.prefersShortLivedTasks();
|
||||
verify(taskExecutorDelegate).prefersShortLivedTasks();
|
||||
}
|
||||
|
||||
protected SchedulingTaskExecutor getExecutor() {
|
||||
return taskExecutorDelegate;
|
||||
}
|
||||
|
||||
protected abstract DelegatingSecurityContextSchedulingTaskExecutor create();
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package org.springframework.security.scheduling;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextSchedulingTaskExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentSecurityContextSchedulingTaskExecutorTests extends AbstractSecurityContextSchedulingTaskExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
protected DelegatingSecurityContextSchedulingTaskExecutor create() {
|
||||
return new DelegatingSecurityContextSchedulingTaskExecutor(taskExecutorDelegate);
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.scheduling;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
|
||||
/**
|
||||
* Tests Explicitly specifying the {@link SecurityContext} on {@link DelegatingSecurityContextSchedulingTaskExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitSecurityContextSchedulingTaskExecutorTests extends AbstractSecurityContextSchedulingTaskExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
protected DelegatingSecurityContextSchedulingTaskExecutor create() {
|
||||
return new DelegatingSecurityContextSchedulingTaskExecutor(taskExecutorDelegate, securityContext);
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.task;
|
||||
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.core.task.AsyncTaskExecutor;
|
||||
import org.springframework.security.concurrent.AbstractDelegatingSecurityContextExecutorTests;
|
||||
|
||||
/**
|
||||
* Abstract class for testing {@link DelegatingSecurityContextAsyncTaskExecutor} which allows customization of
|
||||
* how {@link DelegatingSecurityContextAsyncTaskExecutor} and its mocks are created.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see CurrentDelegatingSecurityContextAsyncTaskExecutorTests
|
||||
* @see ExplicitDelegatingSecurityContextAsyncTaskExecutorTests
|
||||
*/
|
||||
public abstract class AbstractDelegatingSecurityContextAsyncTaskExecutorTests extends AbstractDelegatingSecurityContextExecutorTests {
|
||||
@Mock
|
||||
protected AsyncTaskExecutor taskExecutorDelegate;
|
||||
|
||||
private DelegatingSecurityContextAsyncTaskExecutor executor;
|
||||
|
||||
@Before
|
||||
public final void setUpExecutor() {
|
||||
executor = create();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executeStartTimeout() {
|
||||
executor.execute(runnable, 1);
|
||||
verify(getExecutor()).execute(wrappedRunnable, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void submit() {
|
||||
executor.submit(runnable);
|
||||
verify(getExecutor()).submit(wrappedRunnable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void submitCallable() {
|
||||
executor.submit(callable);
|
||||
verify(getExecutor()).submit(wrappedCallable);
|
||||
}
|
||||
|
||||
protected AsyncTaskExecutor getExecutor() {
|
||||
return taskExecutorDelegate;
|
||||
}
|
||||
|
||||
protected abstract DelegatingSecurityContextAsyncTaskExecutor create();
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package org.springframework.security.task;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextAsyncTaskExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentDelegatingSecurityContextAsyncTaskExecutorTests extends
|
||||
AbstractDelegatingSecurityContextAsyncTaskExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextAsyncTaskExecutor create() {
|
||||
return new DelegatingSecurityContextAsyncTaskExecutor(taskExecutorDelegate);
|
||||
}
|
||||
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.task;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||
import org.springframework.security.concurrent.AbstractDelegatingSecurityContextExecutorTests;
|
||||
|
||||
|
||||
/**
|
||||
* Tests using the current {@link SecurityContext} on {@link DelegatingSecurityContextExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class CurrentDelegatingSecurityContextTaskExecutorTests extends AbstractDelegatingSecurityContextExecutorTests {
|
||||
@Mock
|
||||
private TaskExecutor taskExecutorDelegate;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
currentSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
protected Executor getExecutor() {
|
||||
return taskExecutorDelegate;
|
||||
}
|
||||
|
||||
protected DelegatingSecurityContextExecutor create() {
|
||||
return new DelegatingSecurityContextTaskExecutor(taskExecutorDelegate);
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package org.springframework.security.task;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
|
||||
/**
|
||||
* Tests using an explicit {@link SecurityContext} on {@link DelegatingSecurityContextAsyncTaskExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitDelegatingSecurityContextAsyncTaskExecutorTests extends
|
||||
AbstractDelegatingSecurityContextAsyncTaskExecutorTests {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DelegatingSecurityContextAsyncTaskExecutor create() {
|
||||
return new DelegatingSecurityContextAsyncTaskExecutor(taskExecutorDelegate, securityContext);
|
||||
}
|
||||
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.task;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||
import org.springframework.security.concurrent.AbstractDelegatingSecurityContextExecutorTests;
|
||||
|
||||
|
||||
/**
|
||||
* Tests using the an explicit {@link SecurityContext} on {@link DelegatingSecurityContextExecutor}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*
|
||||
*/
|
||||
public class ExplicitDelegatingSecurityContextTaskExecutorTests extends AbstractDelegatingSecurityContextExecutorTests {
|
||||
@Mock
|
||||
private TaskExecutor taskExecutorDelegate;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
explicitSecurityContextPowermockSetup();
|
||||
}
|
||||
|
||||
protected Executor getExecutor() {
|
||||
return taskExecutorDelegate;
|
||||
}
|
||||
|
||||
protected DelegatingSecurityContextExecutor create() {
|
||||
return new DelegatingSecurityContextTaskExecutor(taskExecutorDelegate, securityContext);
|
||||
}
|
||||
}
|
||||
@@ -494,7 +494,7 @@
|
||||
interested in and to configure how they should be handled. It is used to construct
|
||||
the <interfacename>FilterInvocationSecurityMetadataSource</interfacename> used by
|
||||
the <classname>FilterSecurityInterceptor</classname>. It is also responsible for
|
||||
configuring a <classname>ChannelAuthenticationFilter</classname> if particular URLs
|
||||
configuring a <classname>ChannelProcessingFilter</classname> if particular URLs
|
||||
need to be accessed by HTTPS, for example. When matching the specified patterns
|
||||
against an incoming request, the matching is done in the order in which the elements
|
||||
are declared. So the most specific matches patterns should come first and the most
|
||||
@@ -544,7 +544,7 @@
|
||||
Alternatively the value <quote>any</quote> can be used when there is no
|
||||
preference. If this attribute is present on any
|
||||
<literal><intercept-url></literal> element, then a
|
||||
<classname>ChannelAuthenticationFilter</classname> will be added to the filter
|
||||
<classname>ChannelProcessingFilter</classname> will be added to the filter
|
||||
stack and its additional dependencies added to the application
|
||||
context.<!--See the chapter on <link
|
||||
xlink:href="#channel-security-config">channel security</link> for an example
|
||||
|
||||
@@ -314,7 +314,7 @@ boolean supports(Class clazz);
|
||||
<programlisting language="xml"><![CDATA[
|
||||
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
|
||||
<constructor-arg ref="roleHierarchy" />
|
||||
</class>
|
||||
</bean>
|
||||
<bean id="roleHierarchy"
|
||||
class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
|
||||
<property name="hierarchy">
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
version=3.2.0.M1
|
||||
version=3.1.4.RELEASE
|
||||
|
||||
@@ -2,7 +2,7 @@ configure(allprojects) {
|
||||
apply plugin: 'idea'
|
||||
apply plugin: 'eclipse-wtp'
|
||||
|
||||
eclipse.project.name = "${project.name}-3.2.x"
|
||||
eclipse.project.name = "${project.name}-3.1.x"
|
||||
}
|
||||
|
||||
configure(javaProjects) {
|
||||
@@ -39,29 +39,10 @@ configure(javaProjects) {
|
||||
}
|
||||
}
|
||||
|
||||
// STS-3057
|
||||
configure(allprojects) {
|
||||
task afterEclipseImport {
|
||||
ext.srcFile = file('.classpath')
|
||||
inputs.file srcFile
|
||||
outputs.dir srcFile
|
||||
|
||||
onlyIf { srcFile.exists() }
|
||||
|
||||
doLast {
|
||||
def classpath = new XmlParser().parse(srcFile)
|
||||
classpath.classpathentry.findAll{ it.@path == 'GROOVY_SUPPORT' }.each { classpath.remove(it) }
|
||||
|
||||
def writer = new FileWriter(srcFile)
|
||||
new XmlNodePrinter(new PrintWriter(writer)).print(classpath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// STS-2723
|
||||
project(':spring-security-samples-aspectj') {
|
||||
task afterEclipseImportAjdtFix {
|
||||
ext.srcFile = afterEclipseImport.srcFile
|
||||
task afterEclipseImport {
|
||||
ext.srcFile = file('.classpath')
|
||||
inputs.file srcFile
|
||||
outputs.dir srcFile
|
||||
|
||||
@@ -82,6 +63,4 @@ project(':spring-security-samples-aspectj') {
|
||||
new XmlNodePrinter(new PrintWriter(writer)).print(classpath)
|
||||
}
|
||||
}
|
||||
afterEclipseImport.dependsOn afterEclipseImportAjdtFix
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ apply plugin: 'eclipse'
|
||||
sourceCompatibility = 1.5
|
||||
targetCompatibility = 1.5
|
||||
|
||||
ext.springVersion = '3.2.0.BUILD-SNAPSHOT'
|
||||
ext.springVersion = '3.0.7.RELEASE'
|
||||
ext.springLdapVersion = '1.3.1.RELEASE'
|
||||
ext.ehcacheVersion = '1.6.2'
|
||||
ext.aspectjVersion = '1.6.10'
|
||||
@@ -16,22 +16,12 @@ ext.slf4jVersion = '1.6.1'
|
||||
ext.logbackVersion = '0.9.29'
|
||||
ext.cglibVersion = '2.2'
|
||||
ext.powerMockVersion = '1.4.12'
|
||||
ext.servletApiVersion = '7.0.33'
|
||||
|
||||
ext.powerMockDependencies = [
|
||||
"org.powermock:powermock-core:$powerMockVersion",
|
||||
"org.powermock:powermock-api-support:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4-common:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4:$powerMockVersion",
|
||||
"org.powermock:powermock-api-mockito:$powerMockVersion",
|
||||
"org.powermock:powermock-reflect:$powerMockVersion"
|
||||
]
|
||||
|
||||
ext.bundlorProperties = [
|
||||
version: version,
|
||||
secRange: "[$version, 3.2.0)",
|
||||
springRange: "[$springVersion, 3.2.0)",
|
||||
aspectjRange: '[1.6.0, 1.7.0)',
|
||||
secRange: "[$version, 3.3.0)",
|
||||
springRange: "[$springVersion, 3.3.0)",
|
||||
aspectjRange: '[1.6.0, 1.8.0)',
|
||||
casRange: '[3.1.1, 3.2.0)',
|
||||
cloggingRange: '[1.0.4, 2.0.0)',
|
||||
ehcacheRange: '[1.4.1, 2.5.0)',
|
||||
@@ -90,8 +80,7 @@ dependencies {
|
||||
|
||||
testCompile 'junit:junit:4.7',
|
||||
'org.mockito:mockito-core:1.8.5',
|
||||
"org.springframework:spring-test:$springVersion",
|
||||
'org.easytesting:fest-assert:1.4'
|
||||
"org.springframework:spring-test:$springVersion"
|
||||
|
||||
// Use slf4j/logback for logging
|
||||
testRuntime "org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
|
||||
@@ -85,12 +85,6 @@ def customizePom(pom, gradleProject) {
|
||||
email = 'rwinch@vmware.com'
|
||||
}
|
||||
}
|
||||
repositories {
|
||||
repository {
|
||||
id 'spring-snapshot'
|
||||
url 'http://repo.springsource.org/libs-snapshot'
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
dependency {
|
||||
artifactId = groupId = 'commons-logging'
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+2
-2
@@ -1,6 +1,6 @@
|
||||
#Fri Nov 30 16:30:08 CST 2012
|
||||
#Fri Sep 21 14:16:44 CDT 2012
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=http\://services.gradle.org/distributions/gradle-1.3-bin.zip
|
||||
distributionUrl=http\://services.gradle.org/distributions/gradle-1.2-bin.zip
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
#!/bin/bash
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies {
|
||||
"org.springframework:spring-beans:$springVersion"
|
||||
|
||||
testCompile project(':spring-security-web'),
|
||||
"org.apache.tomcat:tomcat-servlet-api:$servletApiVersion",
|
||||
'javax.servlet:servlet-api:2.5',
|
||||
"org.springframework:spring-web:$springVersion"
|
||||
testRuntime project(':spring-security-config')
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ dependencies {
|
||||
compile "org.springframework:spring-context:$springVersion",
|
||||
"org.springframework:spring-web:$springVersion"
|
||||
|
||||
provided "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
provided 'javax.servlet:servlet-api:2.5'
|
||||
|
||||
testCompile project(':spring-security-core'),
|
||||
project(':spring-security-web'),
|
||||
|
||||
+53
-10
@@ -1,26 +1,69 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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.ldap.server;
|
||||
|
||||
import org.apache.directory.shared.ldap.name.LdapDN;
|
||||
import static junit.framework.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Useful for debugging the container by itself.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @since 3.0
|
||||
*/
|
||||
public class ApacheDSContainerTests {
|
||||
|
||||
// SEC-2162
|
||||
@Test
|
||||
public void successfulStartupAndShutdown() throws Exception {
|
||||
LdapDN people = new LdapDN("ou=people,dc=springframework,dc=org");
|
||||
people.toString();
|
||||
public void failsToStartThrowsException() throws Exception {
|
||||
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
|
||||
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
|
||||
try {
|
||||
server1.afterPropertiesSet();
|
||||
try {
|
||||
server2.afterPropertiesSet();
|
||||
fail("Expected Exception");
|
||||
} catch(RuntimeException success) {}
|
||||
} finally {
|
||||
try {
|
||||
server1.destroy();
|
||||
}catch(Throwable t) {}
|
||||
try {
|
||||
server2.destroy();
|
||||
}catch(Throwable t) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
|
||||
// server.afterPropertiesSet();
|
||||
//
|
||||
// server.getService().getAdminSession().lookup(people);
|
||||
//
|
||||
// server.stop();
|
||||
// SEC-2161
|
||||
@Test
|
||||
public void multipleInstancesSimultanciously() throws Exception {
|
||||
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
|
||||
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
|
||||
try {
|
||||
server1.afterPropertiesSet();
|
||||
server2.afterPropertiesSet();
|
||||
} finally {
|
||||
try {
|
||||
server1.destroy();
|
||||
}catch(Throwable t) {}
|
||||
try {
|
||||
server2.destroy();
|
||||
}catch(Throwable t) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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.ldap.server;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -50,6 +64,7 @@ import org.springframework.util.Assert;
|
||||
* framework public API.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class ApacheDSContainer implements InitializingBean, DisposableBean, Lifecycle, ApplicationContextAware {
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
@@ -103,7 +118,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
|
||||
String apacheWorkDir = System.getProperty("apacheDSWorkDir");
|
||||
|
||||
if (apacheWorkDir == null) {
|
||||
apacheWorkDir = System.getProperty("java.io.tmpdir") + File.separator + "apacheds-spring-security";
|
||||
apacheWorkDir = createTempDirectory("apacheds-spring-security-");
|
||||
}
|
||||
|
||||
setWorkingDirectory(new File(apacheWorkDir));
|
||||
@@ -162,8 +177,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
|
||||
service.startup();
|
||||
server.start();
|
||||
} catch (Exception e) {
|
||||
logger.error("Server startup failed ", e);
|
||||
return;
|
||||
throw new RuntimeException("Server startup failed", e);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -252,6 +266,22 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
|
||||
}
|
||||
}
|
||||
|
||||
private String createTempDirectory(String prefix) throws IOException {
|
||||
String parentTempDir = System.getProperty("java.io.tmpdir");
|
||||
String fileNamePrefix = prefix + System.nanoTime();
|
||||
String fileName = fileNamePrefix;
|
||||
|
||||
for(int i=0;i<1000;i++) {
|
||||
File tempDir = new File(parentTempDir, fileName);
|
||||
if(!tempDir.exists()) {
|
||||
return tempDir.getAbsolutePath();
|
||||
}
|
||||
fileName = fileNamePrefix + "~" + i;
|
||||
}
|
||||
|
||||
throw new IOException("Failed to create a temporary directory for file at " + new File(parentTempDir, fileNamePrefix));
|
||||
}
|
||||
|
||||
private boolean deleteDir(File dir) {
|
||||
if (dir.isDirectory()) {
|
||||
String[] children = dir.list();
|
||||
|
||||
@@ -16,7 +16,7 @@ dependencies {
|
||||
}
|
||||
compile 'com.google.inject:guice:2.0'
|
||||
|
||||
provided "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
provided 'javax.servlet:servlet-api:2.5'
|
||||
|
||||
runtime 'org.apache.httpcomponents:httpclient:4.1.1'
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ eclipse.classpath.plusConfigurations += configurations.integrationTestRuntime
|
||||
dependencies {
|
||||
groovy 'org.codehaus.groovy:groovy:1.8.7'
|
||||
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-cas'),
|
||||
|
||||
@@ -9,7 +9,7 @@ configurations {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-acl'),
|
||||
|
||||
@@ -21,7 +21,7 @@ repositories {
|
||||
configurations.runtime.exclude(group: 'ch.qos.logback')
|
||||
|
||||
dependencies {
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-web'),
|
||||
|
||||
@@ -14,7 +14,7 @@ configurations {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
"org.springframework:spring-beans:$springVersion",
|
||||
|
||||
@@ -7,7 +7,7 @@ dependencies {
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-openid')
|
||||
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
runtime project(':spring-security-config'),
|
||||
project(':spring-security-taglibs'),
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
// Servlet API integration sample build file
|
||||
|
||||
apply plugin: 'war'
|
||||
|
||||
def excludeModules = ['spring-security-acl', 'jsr250-api', 'ehcache', 'spring-jdbc', 'spring-tx']
|
||||
|
||||
configurations {
|
||||
excludeModules.each {name ->
|
||||
runtime.exclude module: name
|
||||
}
|
||||
|
||||
runtime.exclude group: 'org.aspectj'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-web'),
|
||||
"javax.servlet:jstl:$jstlVersion",
|
||||
"org.springframework:spring-beans:$springVersion",
|
||||
"org.springframework:spring-context:$springVersion",
|
||||
"org.springframework:spring-web:$springVersion",
|
||||
"org.springframework:spring-webmvc:$springVersion"
|
||||
|
||||
runtime project(':spring-security-config'),
|
||||
project(':spring-security-taglibs'),
|
||||
"org.springframework:spring-context-support:$springVersion",
|
||||
"javax.servlet:jstl:$jstlVersion",
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
"ch.qos.logback:logback-classic:$logbackVersion"
|
||||
}
|
||||
|
||||
eclipse.wtp.component.contextPath = "servletapi"
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.samples.servletapi.mvc;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public class LoginForm {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
-192
@@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.samples.servletapi.mvc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.Principal;
|
||||
|
||||
import javax.naming.AuthenticationException;
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.access.ExceptionTranslationFilter;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* A Spring MVC Controller that demonstrates Spring Security's integration with the standard Servlet API's. Specifically
|
||||
* it demonstrates the following:
|
||||
* <ul>
|
||||
* <li>{@link #authenticate(HttpServletRequest, HttpServletResponse)} - Integration with
|
||||
* {@link HttpServletRequest#authenticate(HttpServletResponse)}</li>
|
||||
* <li>{@link #login(HttpServletRequest, HttpServletResponse, LoginForm, BindingResult)} - Integration with
|
||||
* {@link HttpServletRequest#login(String, String)}</li>
|
||||
* <li>{@link #logout(HttpServletRequest, HttpServletResponse)} - Integration with {@link HttpServletRequest#logout()}</li>
|
||||
* <li>{@link #remoteUser(HttpServletRequest)} - Integration with {@link HttpServletRequest#getRemoteUser()}</li>
|
||||
* <li>{@link #userPrincipal(HttpServletRequest)} - Integration with {@link HttpServletRequest#getUserPrincipal()}</li>
|
||||
* <li>{@link #authentication(Authentication)} - Spring MVC's ability to resolve the {@link Authentication} since it is
|
||||
* found on {@link HttpServletRequest#getUserPrincipal()}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@Controller
|
||||
public class ServletApiController {
|
||||
/**
|
||||
* Demonstrates that {@link HttpServletRequest#authenticate(HttpServletResponse)} will send the user to the log in
|
||||
* page configured within Spring Security if the user is not already authenticated.
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
* @return
|
||||
* @throws ServletException
|
||||
* @throws IOException
|
||||
*/
|
||||
@RequestMapping("/authenticate")
|
||||
public String authenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
boolean authenticate = request.authenticate(response);
|
||||
return authenticate ? "index" : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates that you can authenticate with Spring Security using
|
||||
* {@link HttpServletRequest#login(String, String)}.
|
||||
*
|
||||
* <p>
|
||||
* If we fail to authenticate, a {@link ServletException} is thrown that wraps the original
|
||||
* {@link AuthenticationException} from Spring Security. This means we can catch the {@link ServletException} to
|
||||
* display the error message. Alternatively, we could allow the {@link ServletException} to propegate and Spring
|
||||
* Security's {@link ExceptionTranslationFilter} would catch it and process it appropriately.
|
||||
* </p>
|
||||
* <p>
|
||||
* In this method we choose to use Spring MVC's {@link ModelAttribute} to make things easier for our form. However,
|
||||
* this is not necessary. We could have just as easily obtained the request parameters from the
|
||||
* {@link HttpServletRequest} object. Remember all of these examples would work in a standard {@link Servlet} or
|
||||
* anything with access to the {@link HttpServletRequest} and {@link HttpServletResponse}.
|
||||
* </p>
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
* @param loginForm
|
||||
* @param result
|
||||
* @return
|
||||
* @throws ServletException
|
||||
*/
|
||||
@RequestMapping(value = "/login", method = RequestMethod.POST)
|
||||
public String login(HttpServletRequest request, HttpServletResponse response,
|
||||
@ModelAttribute LoginForm loginForm, BindingResult result) throws ServletException {
|
||||
try {
|
||||
request.login(loginForm.getUsername(), loginForm.getPassword());
|
||||
} catch(ServletException authenticationFailed) {
|
||||
result.rejectValue(null, "authentication.failed", authenticationFailed.getMessage());
|
||||
return "login";
|
||||
}
|
||||
return "redirect:/";
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates that invoking {@link HttpServletRequest#logout()} will log the user out. Note that the response does
|
||||
* not get processed, so you need to write something to the response.
|
||||
* @param request
|
||||
* @param response
|
||||
* @param redirect
|
||||
* @return
|
||||
* @throws ServletException
|
||||
*/
|
||||
@RequestMapping("/logout")
|
||||
public String logout(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirect) throws ServletException {
|
||||
request.logout();
|
||||
return "redirect:/";
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates Spring Security with {@link AsyncContext#start(Runnable)}. Spring Security will automatically
|
||||
* transfer the {@link SecurityContext} from the thread that {@link AsyncContext#start(Runnable)} is invoked to the
|
||||
* new Thread that invokes the {@link Runnable}.
|
||||
* @param request
|
||||
* @param response
|
||||
*/
|
||||
@RequestMapping("/async")
|
||||
public void asynch(HttpServletRequest request, HttpServletResponse response) {
|
||||
final AsyncContext async = request.startAsync();
|
||||
async.start(new Runnable() {
|
||||
public void run() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
try {
|
||||
final HttpServletResponse asyncResponse = (HttpServletResponse) async.getResponse();
|
||||
asyncResponse.setStatus(HttpServletResponse.SC_OK);
|
||||
asyncResponse.getWriter().write(String.valueOf(authentication));
|
||||
async.complete();
|
||||
} catch(Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates that Spring Security automatically populates {@link HttpServletRequest#getRemoteUser()} with the
|
||||
* current username.
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@ModelAttribute("remoteUser")
|
||||
public String remoteUser(HttpServletRequest request) {
|
||||
return request.getRemoteUser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates that Spring Security automatically populates {@link HttpServletRequest#getUserPrincipal()} with the
|
||||
* {@link Authentication} that is present on {@link SecurityContextHolder#getContext()}
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@ModelAttribute("userPrincipal")
|
||||
public Principal userPrincipal(HttpServletRequest request) {
|
||||
return request.getUserPrincipal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Spring MVC will automatically resolve any object that implements {@link Principal} using
|
||||
* {@link HttpServletRequest#getUserPrincipal()}. This means you can easily resolve the {@link Authentication} just
|
||||
* by adding it as an argument to your MVC controller. Alternatively, you could also have an argument of type
|
||||
* {@link Principal} which would not couple your controller to Spring Security.
|
||||
* @param authentication
|
||||
* @return
|
||||
*/
|
||||
@ModelAttribute
|
||||
public Authentication authentication(Authentication authentication) {
|
||||
return authentication;
|
||||
}
|
||||
|
||||
@RequestMapping("/")
|
||||
public String welcome() {
|
||||
return "index";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/login", method = RequestMethod.GET)
|
||||
public String login(@ModelAttribute LoginForm loginForm) {
|
||||
return "login";
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
xsi:schemaLocation="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://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
|
||||
|
||||
<http auto-config="true" use-expressions="true">
|
||||
<intercept-url pattern="/**" access="permitAll"/>
|
||||
</http>
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
<user name="user" password="password" authorities="ROLE_USER" />
|
||||
<user name="admin" password="password" authorities="ROLE_USER,ROLE_ADMIN"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
</b:beans>
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<b:beans xmlns="http://www.springframework.org/schema/mvc"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:b="http://www.springframework.org/schema/beans"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
|
||||
|
||||
<context:component-scan base-package="org.springframework.security.samples.servletapi.mvc" />
|
||||
|
||||
<!-- Enables the Spring MVC @Controller programming model -->
|
||||
<annotation-driven/>
|
||||
|
||||
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
|
||||
<resources mapping="/resources/**" location="/resources/" />
|
||||
|
||||
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
|
||||
<b:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
|
||||
p:prefix="/WEB-INF/views/"
|
||||
p:suffix=".jsp" />
|
||||
|
||||
</b:beans>
|
||||
@@ -1,44 +0,0 @@
|
||||
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Welcome</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Home Page</h1>
|
||||
<p>
|
||||
Anyone can view this page.
|
||||
</p>
|
||||
|
||||
<sec:authorize access="authenticated" var="authenticated"/>
|
||||
<c:if test="${authenticated}">
|
||||
<p>You are currently authenticated</p>
|
||||
<dl>
|
||||
<dt>HttpServletRequest.getRemoteUser()</dt>
|
||||
<dd><c:out value="${remoteUser}"/></dd>
|
||||
<dt>HttpServletRequest.getUserPrincipal()</dt>
|
||||
<dd><c:out value="${userPrincipal}"/></dd>
|
||||
<dt>Authentication</dt>
|
||||
<dd><c:out value="${authentication}"/></dd>
|
||||
</dl>
|
||||
</c:if>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="<c:url value="/authenticate"/>">HttpServletRequest.authenticate(HttpServletResponse)</a>
|
||||
- if you are authenticated already will simply return true. Otherwise, will redirect you to the log in page configured in your Spring Security configuration.
|
||||
</li>
|
||||
<li>
|
||||
<a href="<c:url value="/async"/>">AsyncContext.start(Runnable)</a>
|
||||
- will automatically transfer the current SecurityContext to the new Thread
|
||||
</li>
|
||||
<c:choose>
|
||||
<c:when test="${authenticated}">
|
||||
<li><a href="<c:url value="/logout"/>">HttpServletRequest.logout()</a></li>
|
||||
</c:when>
|
||||
<c:otherwise>
|
||||
<li><a href="<c:url value="/login"/>">Fill out log in form</a> - allows the user to invoke HttpServletRequest.login(String,String)</li>
|
||||
</c:otherwise>
|
||||
</c:choose>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
|
||||
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Please Log In</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Please Log In</h1>
|
||||
<p>This page demonstrates the use of HttpServletRequest.login(String,String) integration with Spring Security.</p>
|
||||
<form:form action="./login" method="post" modelAttribute="loginForm">
|
||||
<form:errors/>
|
||||
<p>
|
||||
<label for="username">Username</label>
|
||||
<form:input path="username"/>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password">Password</label>
|
||||
<form:password path="password"/>
|
||||
</p>
|
||||
<p>
|
||||
<input type="submit" value="Log In"/>
|
||||
</p>
|
||||
</form:form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,57 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
version="3.0">
|
||||
|
||||
<!--
|
||||
- Location of the XML file that defines the root application context
|
||||
- Applied by ContextLoaderListener.
|
||||
-->
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>
|
||||
classpath:applicationContext-security.xml
|
||||
</param-value>
|
||||
</context-param>
|
||||
|
||||
<!-- Nothing below here needs to be modified -->
|
||||
|
||||
<context-param>
|
||||
<param-name>webAppRootKey</param-name>
|
||||
<param-value>servletapi.root</param-value>
|
||||
</context-param>
|
||||
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
<async-supported>true</async-supported>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
<dispatcher>REQUEST</dispatcher>
|
||||
<dispatcher>ASYNC</dispatcher>
|
||||
</filter-mapping>
|
||||
|
||||
<!--
|
||||
- Loads the root application context of this web app at startup.
|
||||
- The application context is then available via
|
||||
- WebApplicationContextUtils.getWebApplicationContext(servletContext).
|
||||
-->
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
<async-supported>true</async-supported>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
</web-app>
|
||||
@@ -14,7 +14,7 @@ configurations {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5@jar'
|
||||
|
||||
compile project(':spring-security-core'),
|
||||
"org.springframework:spring-beans:$springVersion",
|
||||
|
||||
@@ -24,9 +24,9 @@ dependencies {
|
||||
'org.aspectj:aspectjrt:1.6.8',
|
||||
'org.hibernate:ejb3-persistence:1.0.2.GA',
|
||||
'javax.persistence:persistence-api:1.0',
|
||||
'org.slf4j:jcl-over-slf4j:1.5.11'
|
||||
'org.slf4j:jcl-over-slf4j:1.5.11'
|
||||
|
||||
providedCompile "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
providedCompile 'javax.servlet:servlet-api:2.5'
|
||||
|
||||
runtime 'org.hibernate:hibernate-entitymanager:3.4.0.GA',
|
||||
"org.springframework:spring-context-support:$springVersion",
|
||||
|
||||
+1
-2
@@ -23,8 +23,7 @@ def String[] samples = [
|
||||
'cas/server',
|
||||
'cas/sample',
|
||||
'ldap',
|
||||
'jaas',
|
||||
'servletapi'
|
||||
'jaas'
|
||||
]
|
||||
|
||||
def String[] itest = [
|
||||
|
||||
@@ -10,8 +10,7 @@ dependencies {
|
||||
"org.springframework:spring-expression:$springVersion",
|
||||
"org.springframework:spring-web:$springVersion"
|
||||
|
||||
provided 'javax.servlet:jsp-api:2.0',
|
||||
"org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
|
||||
provided 'javax.servlet:jsp-api:2.0', 'javax.servlet:servlet-api:2.5'
|
||||
|
||||
testRuntime "javax.servlet:jstl:$jstlVersion"
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
/* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,18 +15,26 @@
|
||||
|
||||
package org.springframework.security.web;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Principal;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.security.web.util.UrlUtils;
|
||||
|
||||
@@ -43,7 +50,6 @@ import org.springframework.security.web.util.UrlUtils;
|
||||
* @author Ben Alex
|
||||
* @author colin sampaleanu
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class FilterInvocation {
|
||||
//~ Static fields ==================================================================================================
|
||||
@@ -141,10 +147,8 @@ public class FilterInvocation {
|
||||
}
|
||||
}
|
||||
|
||||
class DummyRequest extends HttpServletRequestWrapper {
|
||||
private static final HttpServletRequest UNSUPPORTED_REQUEST = (HttpServletRequest) Proxy.newProxyInstance(
|
||||
DummyRequest.class.getClassLoader(), new Class[] { HttpServletRequest.class }, new UnsupportedOperationExceptionInvocationHandler());
|
||||
|
||||
@SuppressWarnings({"unchecked", "deprecation"})
|
||||
class DummyRequest implements HttpServletRequest {
|
||||
private String requestURI;
|
||||
private String contextPath = "";
|
||||
private String servletPath;
|
||||
@@ -152,10 +156,6 @@ class DummyRequest extends HttpServletRequestWrapper {
|
||||
private String queryString;
|
||||
private String method;
|
||||
|
||||
public DummyRequest() {
|
||||
super(UNSUPPORTED_REQUEST);
|
||||
}
|
||||
|
||||
public void setRequestURI(String requestURI) {
|
||||
this.requestURI = requestURI;
|
||||
}
|
||||
@@ -203,10 +203,330 @@ class DummyRequest extends HttpServletRequestWrapper {
|
||||
public void setQueryString(String queryString) {
|
||||
this.queryString = queryString;
|
||||
}
|
||||
|
||||
|
||||
public String getAuthType() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Cookie[] getCookies() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public long getDateHeader(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getHeader(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Enumeration getHeaderNames() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Enumeration getHeaders(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getIntHeader(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getPathTranslated() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getRemoteUser() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public StringBuffer getRequestURL() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getRequestedSessionId() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public HttpSession getSession() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public HttpSession getSession(boolean create) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Principal getUserPrincipal() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromCookie() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromURL() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromUrl() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdValid() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isUserInRole(String role) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Enumeration getAttributeNames() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getContentLength() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public ServletInputStream getInputStream() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getLocalAddr() {
|
||||
throw new UnsupportedOperationException();
|
||||
|
||||
}
|
||||
|
||||
public String getLocalName() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getLocalPort() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Enumeration getLocales() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getParameter(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Map getParameterMap() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Enumeration getParameterNames() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String[] getParameterValues(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public BufferedReader getReader() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getRealPath(String path) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getRemoteAddr() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getRemoteHost() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getRemotePort() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public RequestDispatcher getRequestDispatcher(String path) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getScheme() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getServerPort() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isSecure() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object o) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
final class UnsupportedOperationExceptionInvocationHandler implements InvocationHandler {
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
throw new UnsupportedOperationException(method + " is not supported");
|
||||
@SuppressWarnings({"deprecation"})
|
||||
class DummyResponse implements HttpServletResponse {
|
||||
public void addCookie(Cookie cookie) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
public void addDateHeader(String name, long date) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void addHeader(String name, String value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void addIntHeader(String name, int value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean containsHeader(String name) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String encodeRedirectURL(String url) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String encodeRedirectUrl(String url) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String encodeURL(String url) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String encodeUrl(String url) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void sendError(int sc) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
|
||||
}
|
||||
|
||||
public void sendError(int sc, String msg) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void sendRedirect(String location) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setDateHeader(String name, long date) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setHeader(String name, String value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setIntHeader(String name, int value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setStatus(int sc) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setStatus(int sc, String sm) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void flushBuffer() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getBufferSize() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public ServletOutputStream getOutputStream() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public PrintWriter getWriter() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isCommitted() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void resetBuffer() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setBufferSize(int size) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String charset) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setContentLength(int len) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setContentType(String type) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setLocale(Locale loc) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
+6
-20
@@ -20,17 +20,14 @@ import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* Base class for response wrappers which encapsulate the logic for storing a security context and which store the
|
||||
* <code>SecurityContext</code> when a <code>sendError()</code>, <code>sendRedirect</code>,
|
||||
* Base class for response wrappers which encapsulate the logic for storing a security context and which
|
||||
* store the <code>SecurityContext</code> when a <code>sendError()</code>, <code>sendRedirect</code>,
|
||||
* <code>getOutputStream().close()</code>, <code>getOutputStream().flush()</code>, <code>getWriter().close()</code>, or
|
||||
* <code>getWriter().flush()</code> happens on the same thread that this
|
||||
* {@link SaveContextOnUpdateOrErrorResponseWrapper} was created. See issue SEC-398 and SEC-2005.
|
||||
* <code>getWriter().flush()</code> happens. See issue SEC-398 and SEC-2005.
|
||||
* <p>
|
||||
* Sub-classes should implement the {@link #saveContext(SecurityContext context)} method.
|
||||
* <p>
|
||||
@@ -42,9 +39,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
* @since 3.0
|
||||
*/
|
||||
public abstract class SaveContextOnUpdateOrErrorResponseWrapper extends HttpServletResponseWrapper {
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final Thread SUPPORTED_THREAD = Thread.currentThread();
|
||||
|
||||
private boolean contextSaved = false;
|
||||
/* See SEC-1052 */
|
||||
@@ -126,19 +120,11 @@ public abstract class SaveContextOnUpdateOrErrorResponseWrapper extends HttpServ
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls <code>saveContext()</code> with the current contents of the <tt>SecurityContextHolder</tt> as long as
|
||||
* {@link #doSaveContext()} is invoked on the same Thread that {@link SaveContextOnUpdateOrErrorResponseWrapper} was
|
||||
* created on. This prevents issues when dealing with Async Web Requests where the {@link SecurityContext} is not
|
||||
* present on the Thread that processes the response.
|
||||
* Calls <code>saveContext()</code> with the current contents of the <tt>SecurityContextHolder</tt>.
|
||||
*/
|
||||
private void doSaveContext() {
|
||||
Thread currentThread = Thread.currentThread();
|
||||
if(SUPPORTED_THREAD == currentThread) {
|
||||
saveContext(SecurityContextHolder.getContext());
|
||||
contextSaved = true;
|
||||
} else if(logger.isDebugEnabled()){
|
||||
logger.debug("Skip saving SecurityContext since processing the HttpServletResponse on a different Thread than the original HttpServletRequest");
|
||||
}
|
||||
saveContext(SecurityContextHolder.getContext());
|
||||
contextSaved = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.context.request.async;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
|
||||
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Allows for integration with Spring MVC's {@link Callable} support.
|
||||
* </p>
|
||||
* <p>
|
||||
* A {@link CallableProcessingInterceptor} that establishes the injected {@link SecurityContext} on the
|
||||
* {@link SecurityContextHolder} when {@link #preProcess(NativeWebRequest, Callable)} is invoked. It also clear out the
|
||||
* {@link SecurityContextHolder} by invoking {@link SecurityContextHolder#clearContext()} in the
|
||||
* {@link #postProcess(NativeWebRequest, Callable, Object)} method.
|
||||
* </p>
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class SecurityContextCallableProcessingInterceptor extends CallableProcessingInterceptorAdapter {
|
||||
private SecurityContext securityContext;
|
||||
|
||||
/**
|
||||
* Create a new {@link SecurityContextCallableProcessingInterceptor} that uses the {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder} at the time {@link #beforeConcurrentHandling(NativeWebRequest, Callable)} is invoked.
|
||||
*/
|
||||
public SecurityContextCallableProcessingInterceptor() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link SecurityContextCallableProcessingInterceptor} with the specified {@link SecurityContext}.
|
||||
* @param securityContext the {@link SecurityContext} to set on the {@link SecurityContextHolder} in
|
||||
* {@link #preProcess(NativeWebRequest, Callable)}. Cannot be null.
|
||||
* @throws IllegalArgumentException if {@link SecurityContext} is null.
|
||||
*/
|
||||
public SecurityContextCallableProcessingInterceptor(SecurityContext securityContext) {
|
||||
Assert.notNull(securityContext, "securityContext cannot be null");
|
||||
setSecurityContext(securityContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) throws Exception {
|
||||
if(securityContext == null) {
|
||||
setSecurityContext(SecurityContextHolder.getContext());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void preProcess(NativeWebRequest request, Callable<T> task) throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private void setSecurityContext(SecurityContext securityContext) {
|
||||
this.securityContext = securityContext;
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.context.request.async;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.web.context.request.async.WebAsyncManager;
|
||||
import org.springframework.web.context.request.async.WebAsyncUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/**
|
||||
* Provides integration between the {@link SecurityContext} and Spring Web's {@link WebAsyncManager} by using the
|
||||
* {@link SecurityContextCallableProcessingInterceptor#beforeConcurrentHandling(org.springframework.web.context.request.NativeWebRequest, Callable)}
|
||||
* to populate the {@link SecurityContext} on the {@link Callable}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @see SecurityContextCallableProcessingInterceptor
|
||||
*/
|
||||
public final class WebAsyncManagerIntegrationFilter extends OncePerRequestFilter {
|
||||
private static final Object CALLABLE_INTERCEPTOR_KEY = new Object();
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
|
||||
|
||||
SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager.getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY);
|
||||
if (securityProcessingInterceptor == null) {
|
||||
asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY,
|
||||
new SecurityContextCallableProcessingInterceptor());
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -110,7 +110,7 @@ public class DefaultSavedRequest implements SavedRequest {
|
||||
}
|
||||
|
||||
// Parameters
|
||||
Map<String,String[]> parameters = request.getParameterMap();
|
||||
Map<String,Object> parameters = request.getParameterMap();
|
||||
|
||||
for(String paramName : parameters.keySet()) {
|
||||
Object paramValues = parameters.get(paramName);
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.servletapi;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Creates a {@link SecurityContextHolderAwareRequestWrapper}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @see SecurityContextHolderAwareRequestWrapper
|
||||
*/
|
||||
final class HttpServlet25RequestFactory implements HttpServletRequestFactory {
|
||||
private final String rolePrefix;
|
||||
|
||||
HttpServlet25RequestFactory(String rolePrefix) {
|
||||
this.rolePrefix = rolePrefix;
|
||||
}
|
||||
|
||||
public HttpServletRequest create(HttpServletRequest request, HttpServletResponse response) {
|
||||
return new SecurityContextHolderAwareRequestWrapper(request, rolePrefix) ;
|
||||
}
|
||||
}
|
||||
-263
@@ -1,263 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.servletapi;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.Principal;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.AsyncListener;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
|
||||
/**
|
||||
* Provides integration with the Servlet 3 APIs in addition to the ones found in {@link HttpServlet25RequestFactory}.
|
||||
* The additional methods that are integrated with can be found below:
|
||||
*
|
||||
* <ul>
|
||||
* <li> {@link HttpServletRequest#authenticate(HttpServletResponse)} - Allows the user to determine if they are
|
||||
* authenticated and if not send the user to the login page. See
|
||||
* {@link #setAuthenticationEntryPoint(AuthenticationEntryPoint)}.</li>
|
||||
* <li> {@link HttpServletRequest#login(String, String)} - Allows the user to authenticate using the
|
||||
* {@link AuthenticationManager}. See {@link #setAuthenticationManager(AuthenticationManager)}.</li>
|
||||
* <li> {@link HttpServletRequest#logout()} - Allows the user to logout using the {@link LogoutHandler}s configured in
|
||||
* Spring Security. See {@link #setLogoutHandlers(List)}.</li>
|
||||
* <li> {@link AsyncContext#start(Runnable)} - Automatically copy the {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder} found on the Thread that invoked {@link AsyncContext#start(Runnable)} to the Thread
|
||||
* that processes the {@link Runnable}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
* @see SecurityContextHolderAwareRequestFilter
|
||||
* @see HttpServlet25RequestFactory
|
||||
* @see Servlet3SecurityContextHolderAwareRequestWrapper
|
||||
* @see SecurityContextAsyncContext
|
||||
*/
|
||||
final class HttpServlet3RequestFactory implements HttpServletRequestFactory {
|
||||
private Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final String rolePrefix;
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
private AuthenticationManager authenticationManager;
|
||||
private List<LogoutHandler> logoutHandlers;
|
||||
|
||||
HttpServlet3RequestFactory(String rolePrefix) {
|
||||
this.rolePrefix = rolePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link AuthenticationEntryPoint} used when integrating {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically, it will be used when {@link HttpServletRequest#authenticate(HttpServletResponse)} is called and the
|
||||
* user is not authenticated.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), then the default container behavior will be be retained when invoking
|
||||
* {@link HttpServletRequest#authenticate(HttpServletResponse)}.
|
||||
* </p>
|
||||
* @param authenticationEntryPoint the {@link AuthenticationEntryPoint} to use when invoking
|
||||
* {@link HttpServletRequest#authenticate(HttpServletResponse)} if the user is not authenticated.
|
||||
*/
|
||||
|
||||
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
this.authenticationEntryPoint = authenticationEntryPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link AuthenticationManager} used when integrating {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically, it will be used when {@link HttpServletRequest#login(String, String)} is invoked to determine if
|
||||
* the user is authenticated.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), then the default container behavior will be retained when invoking
|
||||
* {@link HttpServletRequest#login(String, String)}.
|
||||
* </p>
|
||||
*
|
||||
* @param authenticationManager the {@link AuthenticationManager} to use when invoking
|
||||
* {@link HttpServletRequest#login(String, String)}
|
||||
*/
|
||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link LogoutHandler}s used when integrating with {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically it will be used when {@link HttpServletRequest#logout()} is invoked in order to log the user out. So
|
||||
* long as the {@link LogoutHandler}s do not commit the {@link HttpServletResponse} (expected), then the user is in
|
||||
* charge of handling the response.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), the default container behavior will be retained when invoking
|
||||
* {@link HttpServletRequest#logout()}.
|
||||
* </p>
|
||||
*
|
||||
* @param logoutHandlers the {@link List<LogoutHandler>}s when invoking {@link HttpServletRequest#logout()}.
|
||||
*/
|
||||
public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) {
|
||||
this.logoutHandlers = logoutHandlers;
|
||||
}
|
||||
|
||||
public HttpServletRequest create(HttpServletRequest request, HttpServletResponse response) {
|
||||
return new Servlet3SecurityContextHolderAwareRequestWrapper(request, rolePrefix, response);
|
||||
}
|
||||
|
||||
private class Servlet3SecurityContextHolderAwareRequestWrapper extends SecurityContextHolderAwareRequestWrapper {
|
||||
private final HttpServletResponse response;
|
||||
|
||||
public Servlet3SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix, HttpServletResponse response) {
|
||||
super(request, rolePrefix);
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
public AsyncContext getAsyncContext() {
|
||||
AsyncContext asyncContext = super.getAsyncContext();
|
||||
return new SecurityContextAsyncContext(asyncContext);
|
||||
}
|
||||
|
||||
public AsyncContext startAsync() {
|
||||
AsyncContext startAsync = super.startAsync();
|
||||
return new SecurityContextAsyncContext(startAsync);
|
||||
}
|
||||
|
||||
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IllegalStateException {
|
||||
AsyncContext startAsync = super.startAsync(servletRequest, servletResponse);
|
||||
return new SecurityContextAsyncContext(startAsync);
|
||||
}
|
||||
|
||||
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
|
||||
AuthenticationEntryPoint entryPoint = authenticationEntryPoint;
|
||||
if(entryPoint == null) {
|
||||
logger.debug("authenticationEntryPoint is null, so allowing original HttpServletRequest to handle authenticate");
|
||||
return super.authenticate(response);
|
||||
}
|
||||
Principal userPrincipal = getUserPrincipal();
|
||||
if(userPrincipal != null) {
|
||||
return true;
|
||||
}
|
||||
entryPoint.commence(this, response, new AuthenticationCredentialsNotFoundException("User is not Authenticated"));
|
||||
return false;
|
||||
}
|
||||
|
||||
public void login(String username, String password) throws ServletException {
|
||||
AuthenticationManager authManager = authenticationManager;
|
||||
if(authManager == null) {
|
||||
logger.debug("authenticationManager is null, so allowing original HttpServletRequest to handle login");
|
||||
super.login(username, password);
|
||||
return;
|
||||
}
|
||||
Authentication authentication;
|
||||
try {
|
||||
authentication = authManager.authenticate(new UsernamePasswordAuthenticationToken(username,password));
|
||||
} catch(AuthenticationException loginFailed) {
|
||||
SecurityContextHolder.clearContext();
|
||||
throw new ServletException(loginFailed.getMessage(), loginFailed);
|
||||
}
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
public void logout() throws ServletException {
|
||||
List<LogoutHandler> handlers = logoutHandlers;
|
||||
if(handlers == null) {
|
||||
logger.debug("logoutHandlers is null, so allowing original HttpServletRequest to handle logout");
|
||||
super.logout();
|
||||
return;
|
||||
}
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
for(LogoutHandler logoutHandler : handlers) {
|
||||
logoutHandler.logout(this, response, authentication);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class SecurityContextAsyncContext implements AsyncContext {
|
||||
private final AsyncContext asyncContext;
|
||||
|
||||
public SecurityContextAsyncContext(AsyncContext asyncContext) {
|
||||
this.asyncContext = asyncContext;
|
||||
}
|
||||
|
||||
public ServletRequest getRequest() {
|
||||
return asyncContext.getRequest();
|
||||
}
|
||||
|
||||
public ServletResponse getResponse() {
|
||||
return asyncContext.getResponse();
|
||||
}
|
||||
|
||||
public boolean hasOriginalRequestAndResponse() {
|
||||
return asyncContext.hasOriginalRequestAndResponse();
|
||||
}
|
||||
|
||||
public void dispatch() {
|
||||
asyncContext.dispatch();
|
||||
}
|
||||
|
||||
public void dispatch(String path) {
|
||||
asyncContext.dispatch(path);
|
||||
}
|
||||
|
||||
public void dispatch(ServletContext context, String path) {
|
||||
asyncContext.dispatch(context, path);
|
||||
}
|
||||
|
||||
public void complete() {
|
||||
asyncContext.complete();
|
||||
}
|
||||
|
||||
public void start(Runnable run) {
|
||||
asyncContext.start(new DelegatingSecurityContextRunnable(run));
|
||||
}
|
||||
|
||||
public void addListener(AsyncListener listener) {
|
||||
asyncContext.addListener(listener);
|
||||
}
|
||||
|
||||
public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
|
||||
asyncContext.addListener(listener, request, response);
|
||||
}
|
||||
|
||||
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
|
||||
return asyncContext.createListener(clazz);
|
||||
}
|
||||
|
||||
public long getTimeout() {
|
||||
return asyncContext.getTimeout();
|
||||
}
|
||||
|
||||
public void setTimeout(long timeout) {
|
||||
asyncContext.setTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.servletapi;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Internal interface for creating a {@link HttpServletRequest}. This allows for creating a different implementation for
|
||||
* Servlet 2.5 and Servlet 3.0 environments.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @see HttpServlet3RequestFactory
|
||||
* @see HttpServlet25RequestFactory
|
||||
*/
|
||||
interface HttpServletRequestFactory {
|
||||
|
||||
/**
|
||||
* Given a {@link HttpServletRequest} returns a {@link HttpServletRequest} that in most cases wraps the original
|
||||
* {@link HttpServletRequest}.
|
||||
* @param request the original {@link HttpServletRequest}. Cannot be null.
|
||||
* @param response the original {@link HttpServletResponse}. Cannot be null.
|
||||
* @return a non-null HttpServletRequest
|
||||
*/
|
||||
public HttpServletRequest create(HttpServletRequest request, HttpServletResponse response);
|
||||
}
|
||||
+4
-122
@@ -1,5 +1,4 @@
|
||||
/* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -17,23 +16,14 @@
|
||||
package org.springframework.security.web.servletapi;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
|
||||
|
||||
@@ -41,134 +31,26 @@ import org.springframework.web.filter.GenericFilterBean;
|
||||
* A <code>Filter</code> which populates the <code>ServletRequest</code> with a request wrapper
|
||||
* which implements the servlet API security methods.
|
||||
* <p>
|
||||
* In pre servlet 3 environment the wrapper class used is {@link SecurityContextHolderAwareRequestWrapper}. See its javadoc for the methods that are implemented.
|
||||
* </p>
|
||||
* <p>
|
||||
* In a servlet 3 environment {@link SecurityContextHolderAwareRequestWrapper} is extended to provide the following additional methods:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li> {@link HttpServletRequest#authenticate(HttpServletResponse)} - Allows the user to determine if they are
|
||||
* authenticated and if not send the user to the login page. See
|
||||
* {@link #setAuthenticationEntryPoint(AuthenticationEntryPoint)}.</li>
|
||||
* <li> {@link HttpServletRequest#login(String, String)} - Allows the user to authenticate using the
|
||||
* {@link AuthenticationManager}. See {@link #setAuthenticationManager(AuthenticationManager)}.</li>
|
||||
* <li> {@link HttpServletRequest#logout()} - Allows the user to logout using the {@link LogoutHandler}s configured in
|
||||
* Spring Security. See {@link #setLogoutHandlers(List)}.</li>
|
||||
* <li> {@link AsyncContext#start(Runnable)} - Automatically copy the {@link SecurityContext} from the
|
||||
* {@link SecurityContextHolder} found on the Thread that invoked {@link AsyncContext#start(Runnable)} to the Thread
|
||||
* that processes the {@link Runnable}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* The wrapper class used is {@link SecurityContextHolderAwareRequestWrapper}.
|
||||
*
|
||||
* @author Orlando Garcia Carmona
|
||||
* @author Ben Alex
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class SecurityContextHolderAwareRequestFilter extends GenericFilterBean {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private String rolePrefix;
|
||||
|
||||
private HttpServletRequestFactory requestFactory;
|
||||
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
private List<LogoutHandler> logoutHandlers;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void setRolePrefix(String rolePrefix) {
|
||||
Assert.notNull(rolePrefix, "Role prefix must not be null");
|
||||
this.rolePrefix = rolePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link AuthenticationEntryPoint} used when integrating {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically, it will be used when {@link HttpServletRequest#authenticate(HttpServletResponse)} is called and the
|
||||
* user is not authenticated.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), then the default container behavior will be be retained when invoking
|
||||
* {@link HttpServletRequest#authenticate(HttpServletResponse)}.
|
||||
* </p>
|
||||
*
|
||||
* @param authenticationEntryPoint the {@link AuthenticationEntryPoint} to use when invoking
|
||||
* {@link HttpServletRequest#authenticate(HttpServletResponse)} if the user is not authenticated.
|
||||
*
|
||||
* @throws IllegalStateException if the Servlet 3 APIs are not found on the classpath
|
||||
*/
|
||||
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
this.authenticationEntryPoint = authenticationEntryPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link AuthenticationManager} used when integrating {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically, it will be used when {@link HttpServletRequest#login(String, String)} is invoked to determine if
|
||||
* the user is authenticated.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), then the default container behavior will be retained when invoking
|
||||
* {@link HttpServletRequest#login(String, String)}.
|
||||
* </p>
|
||||
*
|
||||
* @param authenticationManager the {@link AuthenticationManager} to use when invoking
|
||||
* {@link HttpServletRequest#login(String, String)}
|
||||
*
|
||||
* @throws IllegalStateException if the Servlet 3 APIs are not found on the classpath
|
||||
*/
|
||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the {@link LogoutHandler}s used when integrating with {@link HttpServletRequest} with Servlet 3 APIs.
|
||||
* Specifically it will be used when {@link HttpServletRequest#logout()} is invoked in order to log the user out. So
|
||||
* long as the {@link LogoutHandler}s do not commit the {@link HttpServletResponse} (expected), then the user is in
|
||||
* charge of handling the response.
|
||||
* </p>
|
||||
* <p>
|
||||
* If the value is null (default), the default container behavior will be retained when invoking
|
||||
* {@link HttpServletRequest#logout()}.
|
||||
* </p>
|
||||
*
|
||||
* @param logoutHandlers the {@link List<LogoutHandler>}s when invoking {@link HttpServletRequest#logout()}.
|
||||
*
|
||||
* @throws IllegalStateException if the Servlet 3 APIs are not found on the classpath
|
||||
*/
|
||||
public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) {
|
||||
this.logoutHandlers = logoutHandlers;
|
||||
this.rolePrefix = rolePrefix.trim();
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
chain.doFilter(requestFactory.create((HttpServletRequest)req, (HttpServletResponse) res), res);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws ServletException {
|
||||
super.afterPropertiesSet();
|
||||
requestFactory = isServlet3() ? createServlet3Factory(rolePrefix) : new HttpServlet25RequestFactory(rolePrefix);
|
||||
}
|
||||
|
||||
private HttpServlet3RequestFactory createServlet3Factory(String rolePrefix) {
|
||||
HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix);
|
||||
factory.setAuthenticationEntryPoint(authenticationEntryPoint);
|
||||
factory.setAuthenticationManager(authenticationManager);
|
||||
factory.setLogoutHandlers(logoutHandlers);
|
||||
return factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the Servlet 3 APIs are detected.
|
||||
* @return
|
||||
*/
|
||||
private boolean isServlet3() {
|
||||
return ClassUtils.hasMethod(ServletRequest.class, "startAsync");
|
||||
chain.doFilter(new SecurityContextHolderAwareRequestWrapper((HttpServletRequest) req, rolePrefix), res);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-7
@@ -33,13 +33,8 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
/**
|
||||
* A Spring Security-aware <code>HttpServletRequestWrapper</code>, which uses the
|
||||
* <code>SecurityContext</code>-defined <code>Authentication</code> object to implement the servlet API security
|
||||
* methods:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #getUserPrincipal()}</li>
|
||||
* <li>{@link SecurityContextHolderAwareRequestWrapper#isUserInRole(String)}</li>
|
||||
* <li>{@link HttpServletRequestWrapper#getRemoteUser()}.</li>
|
||||
* </ul>
|
||||
* methods {@link SecurityContextHolderAwareRequestWrapper#isUserInRole(String)} and {@link
|
||||
* HttpServletRequestWrapper#getRemoteUser()}.
|
||||
*
|
||||
* @see SecurityContextHolderAwareRequestFilter
|
||||
*
|
||||
|
||||
+6
-18
@@ -1,23 +1,13 @@
|
||||
package org.springframework.security.web.authentication.rememberme;
|
||||
|
||||
import static org.powermock.api.mockito.PowerMockito.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
|
||||
@@ -29,16 +19,17 @@ import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
|
||||
import org.springframework.security.web.authentication.rememberme.CookieTheftException;
|
||||
import org.springframework.security.web.authentication.rememberme.InvalidCookieException;
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareOnlyThisForTest(ReflectionUtils.class)
|
||||
public class AbstractRememberMeServicesTests {
|
||||
static User joe = new User("joe", "password", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
|
||||
@@ -342,9 +333,6 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void setHttpOnlyIgnoredForServlet25() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
when(ReflectionUtils.findMethod(Cookie.class,"setHttpOnly", boolean.class)).thenReturn(null);
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
|
||||
|
||||
-261
@@ -1,261 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.context;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SaveContextOnUpdateOrErrorResponseWrapperTests {
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private SaveContextOnUpdateOrErrorResponseWrapperStub wrappedResponse;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
response = new MockHttpServletResponse();
|
||||
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response, true);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
wrappedResponse.sendError(error);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.sendError(error);
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorWithMessageSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
String message = "Forbidden";
|
||||
wrappedResponse.sendError(error, message);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorWithMessageSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
final String message = "Forbidden";
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.sendError(error, message);
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectSavesSecurityContext() throws Exception {
|
||||
String url = "/location";
|
||||
wrappedResponse.sendRedirect(url);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
final String url = "/location";
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.sendRedirect(url);
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputFlushSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputCloseSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.getOutputStream().close();
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerFlushSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.getWriter().flush();
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerCloseSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.getWriter().close();
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flushBufferSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.flushBuffer();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flushBufferSkipsSaveSecurityContextOnNewThread() throws Exception {
|
||||
Thread t = new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
wrappedResponse.flushBuffer();
|
||||
} catch(IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
t.join();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
private static class SaveContextOnUpdateOrErrorResponseWrapperStub extends SaveContextOnUpdateOrErrorResponseWrapper {
|
||||
private SecurityContext securityContext;
|
||||
|
||||
public SaveContextOnUpdateOrErrorResponseWrapperStub(HttpServletResponse response, boolean disableUrlRewriting) {
|
||||
super(response, disableUrlRewriting);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveContext(SecurityContext context) {
|
||||
securityContext = context;
|
||||
}
|
||||
}
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.context.request.async;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SecurityContextCallableProcessingInterceptorTests {
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private Callable<?> callable;
|
||||
@Mock
|
||||
private NativeWebRequest webRequest;
|
||||
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNull() {
|
||||
new SecurityContextCallableProcessingInterceptor(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void currentSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor();
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
interceptor.beforeConcurrentHandling(webRequest, callable);
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(
|
||||
securityContext);
|
||||
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
}
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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.web.context.request.async;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.core.task.SimpleAsyncTaskExecutor;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.context.request.async.AsyncWebRequest;
|
||||
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
|
||||
import org.springframework.web.context.request.async.WebAsyncManager;
|
||||
import org.springframework.web.context.request.async.WebAsyncUtils;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class WebAsyncManagerIntegrationFilterTests {
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
@Mock
|
||||
private AsyncWebRequest asyncWebRequest;
|
||||
private WebAsyncManager asyncManager;
|
||||
private JoinableThreadFactory threadFactory;
|
||||
|
||||
private MockFilterChain filterChain;
|
||||
|
||||
private WebAsyncManagerIntegrationFilter filter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(asyncWebRequest.getNativeRequest(HttpServletRequest.class)).thenReturn(request);
|
||||
when(request.getRequestURI()).thenReturn("/");
|
||||
filterChain = new MockFilterChain();
|
||||
|
||||
threadFactory = new JoinableThreadFactory();
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
|
||||
executor.setThreadFactory(threadFactory);
|
||||
|
||||
asyncManager = WebAsyncUtils.getAsyncManager(request);
|
||||
asyncManager.setAsyncWebRequest(asyncWebRequest);
|
||||
asyncManager.setTaskExecutor(executor);
|
||||
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(asyncManager);
|
||||
|
||||
filter = new WebAsyncManagerIntegrationFilter();
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
|
||||
@Override
|
||||
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult)
|
||||
throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception {
|
||||
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
|
||||
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
|
||||
@Override
|
||||
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult)
|
||||
throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
private static final class JoinableThreadFactory implements ThreadFactory {
|
||||
private Thread t;
|
||||
|
||||
public Thread newThread(Runnable r) {
|
||||
t = new Thread(r);
|
||||
return t;
|
||||
}
|
||||
|
||||
public void join() throws InterruptedException {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
|
||||
private class VerifyingCallable implements Callable<SecurityContext> {
|
||||
|
||||
public SecurityContext call() throws Exception {
|
||||
return SecurityContextHolder.getContext();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -35,7 +35,6 @@ import javax.security.auth.login.AppConfigurationEntry;
|
||||
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
|
||||
import javax.security.auth.login.Configuration;
|
||||
import javax.security.auth.login.LoginContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
@@ -192,7 +191,7 @@ public class JaasApiIntegrationFilterTests {
|
||||
|
||||
private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception {
|
||||
MockFilterChain chain = new MockFilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
public void doFilter(ServletRequest request, ServletResponse response) {
|
||||
// See if the subject was updated
|
||||
Subject currentSubject = Subject.getSubject(AccessController.getContext());
|
||||
assertEquals(expectedValue, currentSubject);
|
||||
|
||||
+4
-274
@@ -1,5 +1,4 @@
|
||||
/* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,101 +15,31 @@
|
||||
|
||||
package org.springframework.security.web.servletapi;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.powermock.api.mockito.PowerMockito.doThrow;
|
||||
import static org.powermock.api.mockito.PowerMockito.mock;
|
||||
import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.powermock.reflect.internal.WhiteboxImpl;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link SecurityContextHolderAwareRequestFilter}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(ClassUtils.class)
|
||||
public class SecurityContextHolderAwareRequestFilterTests {
|
||||
@Captor
|
||||
private ArgumentCaptor<HttpServletRequest> requestCaptor;
|
||||
@Mock
|
||||
private AuthenticationManager authenticationManager;
|
||||
@Mock
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
@Mock
|
||||
private LogoutHandler logoutHandler;
|
||||
@Mock
|
||||
private FilterChain filterChain;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private List<LogoutHandler> logoutHandlers;
|
||||
|
||||
private SecurityContextHolderAwareRequestFilter filter;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logoutHandlers = Arrays.asList(logoutHandler);
|
||||
filter = new SecurityContextHolderAwareRequestFilter();
|
||||
filter.setAuthenticationEntryPoint(authenticationEntryPoint);
|
||||
filter.setAuthenticationManager(authenticationManager);
|
||||
filter.setLogoutHandlers(logoutHandlers);
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void expectedRequestWrapperClassIsUsed() throws Exception {
|
||||
SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
|
||||
filter.setRolePrefix("ROLE_");
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
|
||||
|
||||
@@ -121,203 +50,4 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
filter.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateFalse() throws Exception {
|
||||
assertThat(wrappedRequest().authenticate(response)).isFalse();
|
||||
verify(authenticationEntryPoint).commence(eq(requestCaptor.getValue()), eq(response), any(AuthenticationException.class));
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(request, times(0)).authenticate(any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateTrue() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test","password","ROLE_USER"));
|
||||
|
||||
assertThat(wrappedRequest().authenticate(response)).isTrue();
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
verify(request, times(0)).authenticate(any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateNullEntryPointFalse() throws Exception {
|
||||
filter.setAuthenticationEntryPoint(null);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
assertThat(wrappedRequest().authenticate(response)).isFalse();
|
||||
verify(request).authenticate(response);
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateNullEntryPointTrue() throws Exception {
|
||||
when(request.authenticate(response)).thenReturn(true);
|
||||
filter.setAuthenticationEntryPoint(null);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
assertThat(wrappedRequest().authenticate(response)).isTrue();
|
||||
verify(request).authenticate(response);
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void login() throws Exception {
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))).thenReturn(expectedAuth);
|
||||
|
||||
wrappedRequest().login(expectedAuth.getName(),String.valueOf(expectedAuth.getCredentials()));
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
|
||||
verifyZeroInteractions(authenticationEntryPoint, logoutHandler);
|
||||
verify(request, times(0)).login(anyString(),anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginFail() throws Exception {
|
||||
AuthenticationException authException = new BadCredentialsException("Invalid");
|
||||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))).thenThrow(authException);
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("should","be cleared","ROLE_USER"));
|
||||
|
||||
try {
|
||||
wrappedRequest().login("invalid","credentials");
|
||||
Assert.fail("Expected Exception");
|
||||
} catch(ServletException success) {
|
||||
assertThat(success.getCause()).isEqualTo(authException);
|
||||
}
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
|
||||
verifyZeroInteractions(authenticationEntryPoint, logoutHandler);
|
||||
verify(request, times(0)).login(anyString(),anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginNullAuthenticationManager() throws Exception {
|
||||
filter.setAuthenticationManager(null);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
String username = "username";
|
||||
String password = "password";
|
||||
|
||||
wrappedRequest().login(username, password);
|
||||
|
||||
verify(request).login(username, password);
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginNullAuthenticationManagerFail() throws Exception {
|
||||
filter.setAuthenticationManager(null);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
String username = "username";
|
||||
String password = "password";
|
||||
ServletException authException = new ServletException("Failed Login");
|
||||
doThrow(authException).when(request).login(username, password);
|
||||
|
||||
try {
|
||||
wrappedRequest().login(username, password);
|
||||
Assert.fail("Expected Exception");
|
||||
} catch(ServletException success) {
|
||||
assertThat(success).isEqualTo(authException);
|
||||
}
|
||||
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logout() throws Exception {
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(expectedAuth);
|
||||
|
||||
HttpServletRequest wrappedRequest = wrappedRequest();
|
||||
wrappedRequest.logout();
|
||||
|
||||
verify(logoutHandler).logout(wrappedRequest, response, expectedAuth);
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(request, times(0)).logout();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutNullLogoutHandler() throws Exception {
|
||||
filter.setLogoutHandlers(null);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
wrappedRequest().logout();
|
||||
|
||||
verify(request).logout();
|
||||
verifyZeroInteractions(authenticationEntryPoint, authenticationManager, logoutHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAsyncContextStart() throws Exception {
|
||||
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
context.setAuthentication(expectedAuth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.getAsyncContext()).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
public void run() {}
|
||||
};
|
||||
|
||||
wrappedRequest().getAsyncContext().start(runnable);
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, SecurityContext.class)).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, Runnable.class)).isEqualTo(runnable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startAsyncStart() throws Exception {
|
||||
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
context.setAuthentication(expectedAuth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.startAsync()).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
public void run() {}
|
||||
};
|
||||
|
||||
wrappedRequest().startAsync().start(runnable);
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, SecurityContext.class)).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, Runnable.class)).isEqualTo(runnable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startAsyncWithRequestResponseStart() throws Exception {
|
||||
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
context.setAuthentication(expectedAuth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.startAsync(request,response)).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
public void run() {}
|
||||
};
|
||||
|
||||
wrappedRequest().startAsync(request, response).start(runnable);
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, SecurityContext.class)).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, Runnable.class)).isEqualTo(runnable);
|
||||
}
|
||||
|
||||
private HttpServletRequest wrappedRequest() throws Exception {
|
||||
filter.doFilter(request, response, filterChain);
|
||||
verify(filterChain).doFilter(requestCaptor.capture(), any(HttpServletResponse.class));
|
||||
|
||||
return requestCaptor.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
+7
-2
@@ -9,13 +9,18 @@ dependencies {
|
||||
"org.springframework:spring-tx:$springVersion",
|
||||
"org.springframework:spring-web:$springVersion"
|
||||
|
||||
provided "org.apache.tomcat:tomcat-servlet-api:$servletApiVersion"
|
||||
provided 'javax.servlet:servlet-api:2.5'
|
||||
|
||||
testCompile project(':spring-security-core').sourceSets.test.output,
|
||||
'commons-codec:commons-codec:1.3',
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
"org.springframework:spring-test:$springVersion",
|
||||
powerMockDependencies
|
||||
"org.powermock:powermock-core:$powerMockVersion",
|
||||
"org.powermock:powermock-api-support:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4-common:$powerMockVersion",
|
||||
"org.powermock:powermock-module-junit4:$powerMockVersion",
|
||||
"org.powermock:powermock-api-mockito:$powerMockVersion",
|
||||
"org.powermock:powermock-reflect:$powerMockVersion"
|
||||
|
||||
testRuntime "hsqldb:hsqldb:$hsqlVersion"
|
||||
}
|
||||
Reference in New Issue
Block a user