1
0
mirror of synced 2026-08-05 17:57:15 +00:00

SEC-2915: Updated Java Code Formatting

This commit is contained in:
Rob Winch
2015-03-23 11:21:19 -05:00
parent 0a2e496a84
commit ae6af5d73c
1420 changed files with 92995 additions and 85097 deletions
@@ -26,27 +26,26 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.Assert;
/**
* The {@link TestSecurityContextHolder} is very similar to
* {@link SecurityContextHolder}, but is necessary for testing. For example, we
* cannot populate the desired {@link SecurityContext} in
* {@link SecurityContextHolder} for web based testing. In a web request, the
* {@link SecurityContextPersistenceFilter} will override the
* The {@link TestSecurityContextHolder} is very similar to {@link SecurityContextHolder},
* but is necessary for testing. For example, we cannot populate the desired
* {@link SecurityContext} in {@link SecurityContextHolder} for web based testing. In a
* web request, the {@link SecurityContextPersistenceFilter} will override the
* {@link SecurityContextHolder} with the value returned by the
* {@link SecurityContextRepository}. At the end of the {@link FilterChain} the
* {@link SecurityContextPersistenceFilter} will clear out the
* {@link SecurityContextHolder}. This means if we make multiple web requests,
* we will not know which {@link SecurityContext} to use on subsequent requests.
* {@link SecurityContextHolder}. This means if we make multiple web requests, we will not
* know which {@link SecurityContext} to use on subsequent requests.
*
* Typical usage is as follows:
*
* <ul>
* <li>Before a test is executed, the {@link TestSecurityContextHolder} is
* populated. Typically this is done using the
* {@link org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener}</li>
* <li>Before a test is executed, the {@link TestSecurityContextHolder} is populated.
* Typically this is done using the
* {@link org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener}
* </li>
* <li>The test is ran. When used with {@link MockMvc} it is typically used with
* {@link SecurityMockMvcRequestPostProcessors#testSecurityContext()}. Which ensures
* the {@link SecurityContext} from {@link TestSecurityContextHolder} is
* properly populated.</li>
* {@link SecurityMockMvcRequestPostProcessors#testSecurityContext()}. Which ensures the
* {@link SecurityContext} from {@link TestSecurityContextHolder} is properly populated.</li>
* <li>After the test is executed, the {@link TestSecurityContextHolder} and the
* {@link SecurityContextHolder} are cleared out</li>
* </ul>
@@ -57,53 +56,54 @@ import org.springframework.util.Assert;
*/
public final class TestSecurityContextHolder {
private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<SecurityContext>();
private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<SecurityContext>();
/**
* Clears the {@link SecurityContext} from {@link TestSecurityContextHolder}
* and {@link SecurityContextHolder}.
*/
public static void clearContext() {
contextHolder.remove();
SecurityContextHolder.clearContext();
}
/**
* Clears the {@link SecurityContext} from {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
*/
public static void clearContext() {
contextHolder.remove();
SecurityContextHolder.clearContext();
}
/**
* Gets the {@link SecurityContext} from {@link TestSecurityContextHolder}.
*
* @return the {@link SecurityContext} from {@link TestSecurityContextHolder}.
*/
public static SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
/**
* Gets the {@link SecurityContext} from {@link TestSecurityContextHolder}.
*
* @return the {@link SecurityContext} from {@link TestSecurityContextHolder}.
*/
public static SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = getDefaultContext();
contextHolder.set(ctx);
}
if (ctx == null) {
ctx = getDefaultContext();
contextHolder.set(ctx);
}
return ctx;
}
return ctx;
}
/**
* Sets the {@link SecurityContext} on {@link TestSecurityContextHolder} and {@link SecurityContextHolder}.
* @param context the {@link SecurityContext} to use
*/
public static void setContext(SecurityContext context) {
Assert.notNull(context,
"Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
SecurityContextHolder.setContext(context);
}
/**
* Sets the {@link SecurityContext} on {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
* @param context the {@link SecurityContext} to use
*/
public static void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
SecurityContextHolder.setContext(context);
}
/**
* Gets the default {@link SecurityContext} by delegating to the {@link SecurityContextHolder}
*
* @return the default {@link SecurityContext}
*/
private static SecurityContext getDefaultContext() {
return SecurityContextHolder.getContext();
}
/**
* Gets the default {@link SecurityContext} by delegating to the
* {@link SecurityContextHolder}
*
* @return the default {@link SecurityContext}
*/
private static SecurityContext getDefaultContext() {
return SecurityContextHolder.getContext();
}
private TestSecurityContextHolder() {
}
private TestSecurityContextHolder() {
}
}
@@ -30,16 +30,17 @@ import org.springframework.test.web.servlet.MockMvc;
/**
* When used with {@link WithSecurityContextTestExecutionListener} this annotation can be
* added to a test method to emulate running with a mocked user. In order to work with {@link MockMvc} The
* {@link SecurityContext} that is used will have the following properties:
* added to a test method to emulate running with a mocked user. In order to work with
* {@link MockMvc} The {@link SecurityContext} that is used will have the following
* properties:
*
* <ul>
* <li>The {@link SecurityContext} created with be that of
* {@link SecurityContextHolder#createEmptyContext()}</li>
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken}
* that uses the username of either {@link #value()} or {@link #username()},
* {@link GrantedAuthority} that are specified by {@link #roles()}, and a
* password specified by {@link #password()}.
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken} that uses
* the username of either {@link #value()} or {@link #username()},
* {@link GrantedAuthority} that are specified by {@link #roles()}, and a password
* specified by {@link #password()}.
* </ul>
*
* @see WithUserDetails
@@ -53,31 +54,33 @@ import org.springframework.test.web.servlet.MockMvc;
@Documented
@WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
public @interface WithMockUser {
/**
* Convenience mechanism for specifying the username. The default is "user". If {@link #username()} is specified it will be used instead of {@link #value()}
* @return
*/
String value() default "user";
/**
* Convenience mechanism for specifying the username. The default is "user". If
* {@link #username()} is specified it will be used instead of {@link #value()}
* @return
*/
String value() default "user";
/**
* The username to be used. Note that {@link #value()} is a synonym for {@link #username()}, but if {@link #username()} is specified it will take precedence.
* @return
*/
String username() default "";
/**
* The username to be used. Note that {@link #value()} is a synonym for
* {@link #username()}, but if {@link #username()} is specified it will take
* precedence.
* @return
*/
String username() default "";
/**
* The roles to use. The default is "USER". A {@link GrantedAuthority} will
* be created for each value within roles. Each value in roles will
* automatically be prefixed with "ROLE_". For example, the default will
* result in "ROLE_USER" being used.
*
* @return
*/
String[] roles() default { "USER" };
/**
* The roles to use. The default is "USER". A {@link GrantedAuthority} will be created
* for each value within roles. Each value in roles will automatically be prefixed
* with "ROLE_". For example, the default will result in "ROLE_USER" being used.
*
* @return
*/
String[] roles() default { "USER" };
/**
* The password to be used. The default is "password".
* @return
*/
String password() default "password";
/**
* The password to be used. The default is "password".
* @return
*/
String password() default "password";
}
@@ -34,24 +34,30 @@ import org.springframework.util.StringUtils;
* @since 4.0
* @see WithMockUser
*/
final class WithMockUserSecurityContextFactory implements WithSecurityContextFactory<WithMockUser> {
final class WithMockUserSecurityContextFactory implements
WithSecurityContextFactory<WithMockUser> {
public SecurityContext createSecurityContext(WithMockUser withUser) {
String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value();
if(username == null) {
throw new IllegalArgumentException(withUser + " cannot have null username on both username and value properites");
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(String role : withUser.roles()) {
if(role.startsWith("ROLE_")) {
throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role);
}
authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
}
User principal = new User(username, withUser.password(), true, true, true, true, authorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
public SecurityContext createSecurityContext(WithMockUser withUser) {
String username = StringUtils.hasLength(withUser.username()) ? withUser
.username() : withUser.value();
if (username == null) {
throw new IllegalArgumentException(withUser
+ " cannot have null username on both username and value properites");
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : withUser.roles()) {
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("roles cannot start with ROLE_ Got "
+ role);
}
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
User principal = new User(username, withUser.password(), true, true, true, true,
authorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}
@@ -28,8 +28,8 @@ import org.springframework.security.core.context.SecurityContext;
/**
* <p>
* An annotation to determine what {@link SecurityContext} to use. The
* {@link #factory()} attribute must be provided with an instance of
* An annotation to determine what {@link SecurityContext} to use. The {@link #factory()}
* attribute must be provided with an instance of
* {@link WithUserDetailsSecurityContextFactory}.
* </p>
*
@@ -40,23 +40,25 @@ import org.springframework.security.core.context.SecurityContext;
*
* <p>
* If you would like to create your own implementation of
* {@link WithSecurityContextFactory} you can do so by implementing the
* interface. You can also use {@link Autowired} and other Spring semantics on
* the {@link WithSecurityContextFactory} implementation.
* {@link WithSecurityContextFactory} you can do so by implementing the interface. You can
* also use {@link Autowired} and other Spring semantics on the
* {@link WithSecurityContextFactory} implementation.
* </p>
*
* @author Rob Winch
* @since 4.0
*/
@Target({ElementType.ANNOTATION_TYPE})
@Target({ ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface WithSecurityContext {
/**
* The {@link WithUserDetailsSecurityContextFactory} to use to create the {@link SecurityContext}. It can contain {@link Autowired} and other Spring annotations.
*
* @return
*/
Class<? extends WithSecurityContextFactory<? extends Annotation>> factory();
/**
* The {@link WithUserDetailsSecurityContextFactory} to use to create the
* {@link SecurityContext}. It can contain {@link Autowired} and other Spring
* annotations.
*
* @return
*/
Class<? extends WithSecurityContextFactory<? extends Annotation>> factory();
}
@@ -22,8 +22,7 @@ import org.springframework.security.test.context.TestSecurityContextHolder;
/**
* An API that works with WithUserTestExcecutionListener for creating a
* {@link SecurityContext} that is populated in the
* {@link TestSecurityContextHolder}.
* {@link SecurityContext} that is populated in the {@link TestSecurityContextHolder}.
*
* @author Rob Winch
*
@@ -35,13 +34,12 @@ import org.springframework.security.test.context.TestSecurityContextHolder;
*/
public interface WithSecurityContextFactory<A extends Annotation> {
/**
* Create a {@link SecurityContext} given an Annotation.
*
* @param annotation
* the {@link Annotation} to create the {@link SecurityContext}
* from. Cannot be null.
* @return the {@link SecurityContext} to use. Cannot be null.
*/
SecurityContext createSecurityContext(A annotation);
/**
* Create a {@link SecurityContext} given an Annotation.
*
* @param annotation the {@link Annotation} to create the {@link SecurityContext}
* from. Cannot be null.
* @return the {@link SecurityContext} to use. Cannot be null.
*/
SecurityContext createSecurityContext(A annotation);
}
@@ -31,8 +31,8 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
import org.springframework.test.web.servlet.MockMvc;
/**
* A {@link TestExecutionListener} that will find annotations that are annotated
* with {@link WithSecurityContext} on a test method or at the class level. If found, the
* A {@link TestExecutionListener} that will find annotations that are annotated with
* {@link WithSecurityContext} on a test method or at the class level. If found, the
* {@link WithSecurityContext#factory()} is used to create a {@link SecurityContext} that
* will be used with this test. If using with {@link MockMvc} the
* {@link SecurityMockMvcRequestPostProcessors#testSecurityContext()} needs to be used
@@ -43,68 +43,68 @@ import org.springframework.test.web.servlet.MockMvc;
*/
@Order(1000)
public class WithSecurityContextTestExecutionListener extends
AbstractTestExecutionListener {
AbstractTestExecutionListener {
/**
* Sets up the {@link SecurityContext} for each test method. First the
* specific method is inspected for a {@link WithSecurityContext} or {@link Annotation}
* that has {@link WithSecurityContext} on it. If that is not found, the class is
* inspected. If still not found, then no {@link SecurityContext} is
* populated.
*/
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
Annotation[] methodAnnotations = AnnotationUtils
.getAnnotations(testContext.getTestMethod());
ApplicationContext context = testContext.getApplicationContext();
SecurityContext securityContext = createSecurityContext(
methodAnnotations, context);
if (securityContext == null) {
Annotation[] classAnnotations = testContext.getTestClass()
.getAnnotations();
securityContext = createSecurityContext(classAnnotations, context);
}
if (securityContext != null) {
TestSecurityContextHolder.setContext(securityContext);
}
}
/**
* Sets up the {@link SecurityContext} for each test method. First the specific method
* is inspected for a {@link WithSecurityContext} or {@link Annotation} that has
* {@link WithSecurityContext} on it. If that is not found, the class is inspected. If
* still not found, then no {@link SecurityContext} is populated.
*/
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
Annotation[] methodAnnotations = AnnotationUtils.getAnnotations(testContext
.getTestMethod());
ApplicationContext context = testContext.getApplicationContext();
SecurityContext securityContext = createSecurityContext(methodAnnotations,
context);
if (securityContext == null) {
Annotation[] classAnnotations = testContext.getTestClass().getAnnotations();
securityContext = createSecurityContext(classAnnotations, context);
}
if (securityContext != null) {
TestSecurityContextHolder.setContext(securityContext);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private SecurityContext createSecurityContext(Annotation[] annotations,
ApplicationContext context) {
for (Annotation a : annotations) {
WithSecurityContext withUser = AnnotationUtils.findAnnotation(
a.annotationType(), WithSecurityContext.class);
if (withUser != null) {
WithSecurityContextFactory factory = createFactory(
withUser, context);
try {
return factory.createSecurityContext(a);
} catch (RuntimeException e) {
throw new IllegalStateException("Unable to create SecurityContext using "+ a, e);
}
}
}
return null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private SecurityContext createSecurityContext(Annotation[] annotations,
ApplicationContext context) {
for (Annotation a : annotations) {
WithSecurityContext withUser = AnnotationUtils.findAnnotation(
a.annotationType(), WithSecurityContext.class);
if (withUser != null) {
WithSecurityContextFactory factory = createFactory(withUser, context);
try {
return factory.createSecurityContext(a);
}
catch (RuntimeException e) {
throw new IllegalStateException(
"Unable to create SecurityContext using " + a, e);
}
}
}
return null;
}
private WithSecurityContextFactory<? extends Annotation> createFactory(
WithSecurityContext withUser, ApplicationContext context) {
Class<? extends WithSecurityContextFactory<? extends Annotation>> clazz = withUser
.factory();
try {
return context.getAutowireCapableBeanFactory().createBean(clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private WithSecurityContextFactory<? extends Annotation> createFactory(
WithSecurityContext withUser, ApplicationContext context) {
Class<? extends WithSecurityContextFactory<? extends Annotation>> clazz = withUser
.factory();
try {
return context.getAutowireCapableBeanFactory().createBean(clazz);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Clears out the {@link TestSecurityContextHolder} and the
* {@link SecurityContextHolder} after each test method.
*/
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
TestSecurityContextHolder.clearContext();
}
/**
* Clears out the {@link TestSecurityContextHolder} and the
* {@link SecurityContextHolder} after each test method.
*/
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
TestSecurityContextHolder.clearContext();
}
}
@@ -32,17 +32,17 @@ import org.springframework.test.web.servlet.MockMvc;
/**
* When used with {@link WithSecurityContextTestExecutionListener} this annotation can be
* added to a test method to emulate running with a {@link UserDetails} returned
* from the {@link UserDetailsService}. In order to work with {@link MockMvc}
* The {@link SecurityContext} that is used will have the following properties:
* added to a test method to emulate running with a {@link UserDetails} returned from the
* {@link UserDetailsService}. In order to work with {@link MockMvc} The
* {@link SecurityContext} that is used will have the following properties:
*
* <ul>
* <li>The {@link SecurityContext} created with be that of
* {@link SecurityContextHolder#createEmptyContext()}</li>
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken}
* that uses the username of either {@link #value()} or {@link #username()},
* {@link GrantedAuthority} that are specified by {@link #roles()}, and a
* password specified by {@link #password()}.
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken} that uses
* the username of either {@link #value()} or {@link #username()},
* {@link GrantedAuthority} that are specified by {@link #roles()}, and a password
* specified by {@link #password()}.
* </ul>
*
* @see WithMockUser
@@ -50,16 +50,16 @@ import org.springframework.test.web.servlet.MockMvc;
* @author Rob Winch
* @since 4.0
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory=WithUserDetailsSecurityContextFactory.class)
@WithSecurityContext(factory = WithUserDetailsSecurityContextFactory.class)
public @interface WithUserDetails {
/**
* The username to look up in the {@link UserDetailsService}
*
* @return
*/
String value() default "user";
/**
* The username to look up in the {@link UserDetailsService}
*
* @return
*/
String value() default "user";
}
@@ -25,7 +25,8 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
/**
* A {@link WithUserDetailsSecurityContextFactory} that works with {@link WithUserDetails}.
* A {@link WithUserDetailsSecurityContextFactory} that works with {@link WithUserDetails}
* .
*
* @see WithUserDetails
*
@@ -33,22 +34,24 @@ import org.springframework.util.Assert;
* @since 4.0
*/
final class WithUserDetailsSecurityContextFactory implements WithSecurityContextFactory<WithUserDetails> {
final class WithUserDetailsSecurityContextFactory implements
WithSecurityContextFactory<WithUserDetails> {
private UserDetailsService userDetailsService;
private UserDetailsService userDetailsService;
@Autowired
public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Autowired
public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public SecurityContext createSecurityContext(WithUserDetails withUser) {
String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
public SecurityContext createSecurityContext(WithUserDetails withUser) {
String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}
@@ -35,179 +35,183 @@ import org.springframework.test.web.servlet.request.RequestPostProcessor;
*/
public final class SecurityMockMvcRequestBuilders {
/**
* Creates a request (including any necessary {@link CsrfToken}) that will
* submit a form based login to POST "/login".
*
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin() {
return new FormLoginRequestBuilder();
}
/**
* Creates a request (including any necessary {@link CsrfToken}) that will submit a
* form based login to POST "/login".
*
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin() {
return new FormLoginRequestBuilder();
}
/**
* Creates a request (including any necessary {@link CsrfToken}) that will
* submit a form based login to POST {@code loginProcessingUrl}.
*
* @param loginProcessingUrl
* the URL to POST to
*
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin(String loginProcessingUrl) {
return formLogin().loginProcessingUrl(loginProcessingUrl);
}
/**
* Creates a request (including any necessary {@link CsrfToken}) that will submit a
* form based login to POST {@code loginProcessingUrl}.
*
* @param loginProcessingUrl the URL to POST to
*
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin(String loginProcessingUrl) {
return formLogin().loginProcessingUrl(loginProcessingUrl);
}
/**
* Creates a logout request.
*
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout() {
return new LogoutRequestBuilder();
}
/**
* Creates a logout request.
*
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout() {
return new LogoutRequestBuilder();
}
/**
* Creates a logout request (including any necessary {@link CsrfToken}) to
* the specified {@code logoutUrl}
*
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout(String logoutUrl) {
return new LogoutRequestBuilder().logoutUrl(logoutUrl);
}
/**
* Creates a logout request (including any necessary {@link CsrfToken}) to the
* specified {@code logoutUrl}
*
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout(String logoutUrl) {
return new LogoutRequestBuilder().logoutUrl(logoutUrl);
}
/**
* Creates a logout request (including any necessary {@link CsrfToken})
*
* @author Rob Winch
* @since 4.0
*/
public static final class LogoutRequestBuilder implements RequestBuilder {
private String logoutUrl = "/logout";
private RequestPostProcessor postProcessor = csrf();
/**
* Creates a logout request (including any necessary {@link CsrfToken})
*
* @author Rob Winch
* @since 4.0
*/
public static final class LogoutRequestBuilder implements RequestBuilder {
private String logoutUrl = "/logout";
private RequestPostProcessor postProcessor = csrf();
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequest request = post(logoutUrl)
.buildRequest(servletContext);
return postProcessor.postProcessRequest(request);
}
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequest request = post(logoutUrl).buildRequest(servletContext);
return postProcessor.postProcessRequest(request);
}
/**
* Specifies the logout URL to POST to. Defaults to "/logout".
*
* @param logoutUrl the logout URL to POST to. Defaults to "/logout".
* @return the {@link LogoutRequestBuilder} for additional customizations
*/
public LogoutRequestBuilder logoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
return this;
}
/**
* Specifies the logout URL to POST to. Defaults to "/logout".
*
* @param logoutUrl the logout URL to POST to. Defaults to "/logout".
* @return the {@link LogoutRequestBuilder} for additional customizations
*/
public LogoutRequestBuilder logoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
return this;
}
private LogoutRequestBuilder() {}
}
private LogoutRequestBuilder() {
}
}
/**
* Creates a form based login request including any necessary {@link CsrfToken}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class FormLoginRequestBuilder implements RequestBuilder {
private String usernameParam = "username";
private String passwordParam = "password";
private String username = "user";
private String password = "password";
private String loginProcessingUrl = "/login";
private RequestPostProcessor postProcessor = csrf();
/**
* Creates a form based login request including any necessary {@link CsrfToken}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class FormLoginRequestBuilder implements RequestBuilder {
private String usernameParam = "username";
private String passwordParam = "password";
private String username = "user";
private String password = "password";
private String loginProcessingUrl = "/login";
private RequestPostProcessor postProcessor = csrf();
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequest request = post(loginProcessingUrl)
.param(usernameParam,username)
.param(passwordParam, password)
.buildRequest(servletContext);
return postProcessor.postProcessRequest(request);
}
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequest request = post(loginProcessingUrl)
.param(usernameParam, username).param(passwordParam, password)
.buildRequest(servletContext);
return postProcessor.postProcessRequest(request);
}
/**
* Specifies the URL to POST to. Default is "/login"
*
* @param loginProcessingUrl the URL to POST to. Default is "/login"
* @return
*/
public FormLoginRequestBuilder loginProcessingUrl(String loginProcessingUrl) {
this.loginProcessingUrl = loginProcessingUrl;
return this;
}
/**
* Specifies the URL to POST to. Default is "/login"
*
* @param loginProcessingUrl the URL to POST to. Default is "/login"
* @return
*/
public FormLoginRequestBuilder loginProcessingUrl(String loginProcessingUrl) {
this.loginProcessingUrl = loginProcessingUrl;
return this;
}
/**
* The HTTP parameter to place the username. Default is "username".
* @param usernameParameter the HTTP parameter to place the username. Default is "username".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder userParameter(String usernameParameter) {
this.usernameParam = usernameParameter;
return this;
}
/**
* The HTTP parameter to place the username. Default is "username".
* @param usernameParameter the HTTP parameter to place the username. Default is
* "username".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder userParameter(String usernameParameter) {
this.usernameParam = usernameParameter;
return this;
}
/**
* The HTTP parameter to place the password. Default is "password".
* @param passwordParameter the HTTP parameter to place the password. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder passwordParam(String passwordParameter) {
this.passwordParam = passwordParameter;
return this;
}
/**
* The HTTP parameter to place the password. Default is "password".
* @param passwordParameter the HTTP parameter to place the password. Default is
* "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder passwordParam(String passwordParameter) {
this.passwordParam = passwordParameter;
return this;
}
/**
* The value of the password parameter. Default is "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String password) {
this.password = password;
return this;
}
/**
* The value of the password parameter. Default is "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String password) {
this.password = password;
return this;
}
/**
* The value of the username parameter. Default is "user".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String username) {
this.username = username;
return this;
}
/**
* The value of the username parameter. Default is "user".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String username) {
this.username = username;
return this;
}
/**
* Specify both the password parameter name and the password.
*
* @param passwordParameter the HTTP parameter to place the password. Default is "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String passwordParameter, String password) {
passwordParam(passwordParameter);
this.password = password;
return this;
}
/**
* Specify both the password parameter name and the password.
*
* @param passwordParameter the HTTP parameter to place the password. Default is
* "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String passwordParameter, String password) {
passwordParam(passwordParameter);
this.password = password;
return this;
}
/**
* Specify both the password parameter name and the password.
*
* @param usernameParameter the HTTP parameter to place the username. Default is "username".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String usernameParameter, String username) {
userParameter(usernameParameter);
this.username = username;
return this;
}
/**
* Specify both the password parameter name and the password.
*
* @param usernameParameter the HTTP parameter to place the username. Default is
* "username".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String usernameParameter, String username) {
userParameter(usernameParameter);
this.username = username;
return this;
}
private FormLoginRequestBuilder() {}
}
private FormLoginRequestBuilder() {
}
}
private SecurityMockMvcRequestBuilders() {}
private SecurityMockMvcRequestBuilders() {
}
}
@@ -40,188 +40,203 @@ import org.springframework.test.web.servlet.ResultMatcher;
*/
public final class SecurityMockMvcResultMatchers {
/**
* {@link ResultMatcher} that verifies that a specified user is
* authenticated.
*
* @return the {@link AuthenticatedMatcher} to use
*/
public static AuthenticatedMatcher authenticated() {
return new AuthenticatedMatcher();
}
/**
* {@link ResultMatcher} that verifies that a specified user is authenticated.
*
* @return the {@link AuthenticatedMatcher} to use
*/
public static AuthenticatedMatcher authenticated() {
return new AuthenticatedMatcher();
}
/**
* {@link ResultMatcher} that verifies that no user is authenticated.
*
* @return the {@link AuthenticatedMatcher} to use
*/
public static ResultMatcher unauthenticated() {
return new UnAuthenticatedMatcher();
}
/**
* {@link ResultMatcher} that verifies that no user is authenticated.
*
* @return the {@link AuthenticatedMatcher} to use
*/
public static ResultMatcher unauthenticated() {
return new UnAuthenticatedMatcher();
}
private static abstract class AuthenticationMatcher<T extends AuthenticationMatcher<T>> implements ResultMatcher {
private static abstract class AuthenticationMatcher<T extends AuthenticationMatcher<T>>
implements ResultMatcher {
protected SecurityContext load(MvcResult result) {
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(result.getRequest(), result.getResponse());
SecurityContextRepository repository = WebTestUtils.getSecurityContextRepository(result.getRequest());
return repository.loadContext(holder);
}
}
protected SecurityContext load(MvcResult result) {
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(
result.getRequest(), result.getResponse());
SecurityContextRepository repository = WebTestUtils
.getSecurityContextRepository(result.getRequest());
return repository.loadContext(holder);
}
}
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies a specific user is
* associated to the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class AuthenticatedMatcher extends AuthenticationMatcher<AuthenticatedMatcher> {
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies a specific user is associated
* to the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class AuthenticatedMatcher extends
AuthenticationMatcher<AuthenticatedMatcher> {
private SecurityContext expectedContext;
private Authentication expectedAuthentication;
private Object expectedAuthenticationPrincipal;
private String expectedAuthenticationName;
private Collection<GrantedAuthority> expectedGrantedAuthorities;
private SecurityContext expectedContext;
private Authentication expectedAuthentication;
private Object expectedAuthenticationPrincipal;
private String expectedAuthenticationName;
private Collection<GrantedAuthority> expectedGrantedAuthorities;
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);
Authentication auth = context.getAuthentication();
Authentication auth = context.getAuthentication();
assertTrue("Authentication should not be null", auth != null);
assertTrue("Authentication should not be null", auth != null);
if (this.expectedContext != null) {
assertEquals(this.expectedContext + " does not equal " + context,
this.expectedContext, context);
}
if(this.expectedContext != null) {
assertEquals(this.expectedContext + " does not equal " + context, this.expectedContext, context);
}
if (this.expectedAuthentication != null) {
assertEquals(
this.expectedAuthentication + " does not equal "
+ context.getAuthentication(),
this.expectedAuthentication, context.getAuthentication());
}
if(this.expectedAuthentication != null) {
assertEquals(this.expectedAuthentication + " does not equal " + context.getAuthentication(), this.expectedAuthentication, context.getAuthentication());
}
if (this.expectedAuthenticationPrincipal != null) {
assertTrue("Authentication cannot be null",
context.getAuthentication() != null);
assertEquals(this.expectedAuthenticationPrincipal + " does not equal "
+ context.getAuthentication().getPrincipal(),
this.expectedAuthenticationPrincipal, context.getAuthentication()
.getPrincipal());
}
if(this.expectedAuthenticationPrincipal != null) {
assertTrue("Authentication cannot be null", context.getAuthentication() != null);
assertEquals(this.expectedAuthenticationPrincipal + " does not equal " + context.getAuthentication().getPrincipal(), this.expectedAuthenticationPrincipal, context.getAuthentication().getPrincipal());
}
if (this.expectedAuthenticationName != null) {
assertTrue("Authentication cannot be null", auth != null);
String name = auth.getName();
assertEquals(this.expectedAuthenticationName + " does not equal " + name,
this.expectedAuthenticationName, name);
}
if(this.expectedAuthenticationName != null) {
assertTrue("Authentication cannot be null", auth != null);
String name = auth.getName();
assertEquals(this.expectedAuthenticationName + " does not equal " + name, this.expectedAuthenticationName, name);
}
if (this.expectedGrantedAuthorities != null) {
assertTrue("Authentication cannot be null", auth != null);
Collection<? extends GrantedAuthority> authorities = auth
.getAuthorities();
assertTrue(authorities + " does not contain the same authorities as "
+ this.expectedGrantedAuthorities,
authorities.containsAll(this.expectedGrantedAuthorities));
assertTrue(this.expectedGrantedAuthorities
+ " does not contain the same authorities as " + authorities,
this.expectedGrantedAuthorities.containsAll(authorities));
}
}
if(this.expectedGrantedAuthorities != null) {
assertTrue("Authentication cannot be null", auth != null);
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
assertTrue(authorities + " does not contain the same authorities as " + this.expectedGrantedAuthorities, authorities.containsAll(this.expectedGrantedAuthorities));
assertTrue(this.expectedGrantedAuthorities + " does not contain the same authorities as " + authorities , this.expectedGrantedAuthorities.containsAll(authorities));
}
}
/**
* Specifies the expected username
*
* @param expected the expected username
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withUsername(String expected) {
return withAuthenticationName(expected);
}
/**
* Specifies the expected username
*
* @param expected
* the expected username
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withUsername(String expected) {
return withAuthenticationName(expected);
}
/**
* Specifies the expected {@link SecurityContext}
*
* @param expected the expected {@link SecurityContext}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withSecurityContext(SecurityContext expected) {
this.expectedContext = expected;
return this;
}
/**
* Specifies the expected {@link SecurityContext}
*
* @param expected
* the expected {@link SecurityContext}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withSecurityContext(SecurityContext expected) {
this.expectedContext = expected;
return this;
}
/**
* Specifies the expected {@link Authentication}
*
* @param expected the expected {@link Authentication}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthentication(Authentication expected) {
this.expectedAuthentication = expected;
return this;
}
/**
* Specifies the expected {@link Authentication}
*
* @param expected
* the expected {@link Authentication}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthentication(Authentication expected) {
this.expectedAuthentication = expected;
return this;
}
/**
* Specifies the expected principal
*
* @param expected the expected principal
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationPrincipal(Object expected) {
this.expectedAuthenticationPrincipal = expected;
return this;
}
/**
* Specifies the expected principal
*
* @param expected
* the expected principal
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationPrincipal(Object expected) {
this.expectedAuthenticationPrincipal = expected;
return this;
}
/**
* Specifies the expected {@link Authentication#getName()}
*
* @param expected the expected {@link Authentication#getName()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationName(String expected) {
this.expectedAuthenticationName = expected;
return this;
}
/**
* Specifies the expected {@link Authentication#getName()}
*
* @param expected
* the expected {@link Authentication#getName()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationName(String expected) {
this.expectedAuthenticationName = expected;
return this;
}
/**
* Specifies the {@link Authentication#getAuthorities()}
*
* @param expected the {@link Authentication#getAuthorities()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthorities(Collection<GrantedAuthority> expected) {
this.expectedGrantedAuthorities = expected;
return this;
}
/**
* Specifies the {@link Authentication#getAuthorities()}
*
* @param expected the {@link Authentication#getAuthorities()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthorities(Collection<GrantedAuthority> expected) {
this.expectedGrantedAuthorities = expected;
return this;
}
/**
* Specifies the {@link Authentication#getAuthorities()}
*
* @param expected the roles. Each value is automatically prefixed with "ROLE_"
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withRoles(String... roles) {
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
return withAuthorities(authorities);
}
/**
* Specifies the {@link Authentication#getAuthorities()}
*
* @param expected the roles. Each value is automatically prefixed with "ROLE_"
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withRoles(String... roles) {
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(String role : roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
}
return withAuthorities(authorities);
}
AuthenticatedMatcher() {
}
}
AuthenticatedMatcher() {}
}
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies no {@link Authentication} is
* associated with the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class UnAuthenticatedMatcher extends
AuthenticationMatcher<UnAuthenticatedMatcher> {
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies no
* {@link Authentication} is associated with the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class UnAuthenticatedMatcher extends AuthenticationMatcher<UnAuthenticatedMatcher>{
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);
assertEquals("", null, context.getAuthentication());
}
assertEquals("",null,context.getAuthentication());
}
private UnAuthenticatedMatcher() {
}
}
private UnAuthenticatedMatcher() {}
}
private SecurityMockMvcResultMatchers() {}
private SecurityMockMvcResultMatchers() {
}
}
@@ -26,40 +26,47 @@ import javax.servlet.Filter;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
/**
* Configures Spring Security by adding the springSecurityFilterChain and adding the {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}.
* Configures Spring Security by adding the springSecurityFilterChain and adding the
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
*
* @author Rob Winch
* @since 4.0
*/
final class SecurityMockMvcConfigurer extends MockMvcConfigurerAdapter {
private Filter springSecurityFilterChain;
private Filter springSecurityFilterChain;
/**
* Creates a new instance
*/
SecurityMockMvcConfigurer() {}
/**
* Creates a new instance
*/
SecurityMockMvcConfigurer() {
}
/**
* Creates a new instance with the provided {@link javax.servlet.Filter}
* @param springSecurityFilterChain the {@link javax.servlet.Filter} to use
*/
SecurityMockMvcConfigurer(Filter springSecurityFilterChain) {
this.springSecurityFilterChain = springSecurityFilterChain;
}
/**
* Creates a new instance with the provided {@link javax.servlet.Filter}
* @param springSecurityFilterChain the {@link javax.servlet.Filter} to use
*/
SecurityMockMvcConfigurer(Filter springSecurityFilterChain) {
this.springSecurityFilterChain = springSecurityFilterChain;
}
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) {
String securityBeanId = BeanIds.SPRING_SECURITY_FILTER_CHAIN;
if(springSecurityFilterChain == null && context.containsBean(securityBeanId)) {
springSecurityFilterChain = context.getBean(securityBeanId, Filter.class);
}
@Override
public RequestPostProcessor beforeMockMvcCreated(
ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) {
String securityBeanId = BeanIds.SPRING_SECURITY_FILTER_CHAIN;
if (springSecurityFilterChain == null && context.containsBean(securityBeanId)) {
springSecurityFilterChain = context.getBean(securityBeanId, Filter.class);
}
if(springSecurityFilterChain == null) {
throw new IllegalStateException("springSecurityFilterChain cannot be null. Ensure a Bean with the name "+ securityBeanId + " implementing Filter is present or inject the Filter to be used.");
}
if (springSecurityFilterChain == null) {
throw new IllegalStateException(
"springSecurityFilterChain cannot be null. Ensure a Bean with the name "
+ securityBeanId
+ " implementing Filter is present or inject the Filter to be used.");
}
builder.addFilters(springSecurityFilterChain);
builder.addFilters(springSecurityFilterChain);
return testSecurityContext();
}
return testSecurityContext();
}
}
@@ -21,34 +21,43 @@ import org.springframework.util.Assert;
import javax.servlet.Filter;
/**
* Provides Security related {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} implementations.
* Provides Security related
* {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} implementations.
*
* @since 4.0
* @author Rob Winch
*/
public final class SecurityMockMvcConfigurers {
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the configurer adds the Spring Bean
* named "springSecurityFilterChain" as a Filter. It will also ensure that the TestSecurityContextHolder is leveraged
* for each request by applying {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}.
*
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to use
*/
public static MockMvcConfigurer springSecurity() {
return new SecurityMockMvcConfigurer();
}
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the
* configurer adds the Spring Bean named "springSecurityFilterChain" as a Filter. It
* will also ensure that the TestSecurityContextHolder is leveraged for each request
* by applying
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
*
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to
* use
*/
public static MockMvcConfigurer springSecurity() {
return new SecurityMockMvcConfigurer();
}
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the configurer adds the provided Filter. It will also ensure that the
* TestSecurityContextHolder is leveraged for each request by applying
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}.
*
* @param springSecurityFilterChain the Filter to be added
*
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to use
*/
public static MockMvcConfigurer springSecurity(Filter springSecurityFilterChain) {
Assert.notNull(springSecurityFilterChain, "springSecurityFilterChain cannot be null");
return new SecurityMockMvcConfigurer(springSecurityFilterChain);
}
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the
* configurer adds the provided Filter. It will also ensure that the
* TestSecurityContextHolder is leveraged for each request by applying
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
*
* @param springSecurityFilterChain the Filter to be added
*
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to
* use
*/
public static MockMvcConfigurer springSecurity(Filter springSecurityFilterChain) {
Assert.notNull(springSecurityFilterChain,
"springSecurityFilterChain cannot be null");
return new SecurityMockMvcConfigurer(springSecurityFilterChain);
}
}
@@ -39,86 +39,92 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
* @since 4.0
*/
public abstract class WebTestUtils {
private static final SecurityContextRepository DEFAULT_CONTEXT_REPO = new HttpSessionSecurityContextRepository();
private static final CsrfTokenRepository DEFAULT_TOKEN_REPO = new HttpSessionCsrfTokenRepository();
private static final SecurityContextRepository DEFAULT_CONTEXT_REPO = new HttpSessionSecurityContextRepository();
private static final CsrfTokenRepository DEFAULT_TOKEN_REPO = new HttpSessionCsrfTokenRepository();
/**
* Gets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}. If one is not found, a default
* {@link HttpSessionSecurityContextRepository} is used.
*
* @param request
* the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @return the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}
*/
public static SecurityContextRepository getSecurityContextRepository(HttpServletRequest request) {
SecurityContextPersistenceFilter filter = findFilter(request, SecurityContextPersistenceFilter.class);
if(filter == null) {
return DEFAULT_CONTEXT_REPO;
}
return (SecurityContextRepository) ReflectionTestUtils.getField(filter, "repo");
}
/**
* Gets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}. If one is not found, a default
* {@link HttpSessionSecurityContextRepository} is used.
*
* @param request the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @return the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}
*/
public static SecurityContextRepository getSecurityContextRepository(
HttpServletRequest request) {
SecurityContextPersistenceFilter filter = findFilter(request,
SecurityContextPersistenceFilter.class);
if (filter == null) {
return DEFAULT_CONTEXT_REPO;
}
return (SecurityContextRepository) ReflectionTestUtils.getField(filter, "repo");
}
/**
* Sets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}.
*
* @param request
* the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @param securityContextRepository
* the {@link SecurityContextRepository} to set
* @return the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}
*/
public static void setSecurityContextRepository(HttpServletRequest request, SecurityContextRepository securityContextRepository) {
SecurityContextPersistenceFilter filter = findFilter(request, SecurityContextPersistenceFilter.class);
if(filter != null) {
ReflectionTestUtils.setField(filter, "repo", securityContextRepository);
}
}
/**
* Sets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}.
*
* @param request the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @param securityContextRepository the {@link SecurityContextRepository} to set
* @return the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}
*/
public static void setSecurityContextRepository(HttpServletRequest request,
SecurityContextRepository securityContextRepository) {
SecurityContextPersistenceFilter filter = findFilter(request,
SecurityContextPersistenceFilter.class);
if (filter != null) {
ReflectionTestUtils.setField(filter, "repo", securityContextRepository);
}
}
/**
* Gets the {@link CsrfTokenRepository} for the specified
* {@link HttpServletRequest}. If one is not found, the default
* {@link HttpSessionCsrfTokenRepository} is used.
*
* @param request
* the {@link HttpServletRequest} to obtain the
* {@link CsrfTokenRepository}
* @return the {@link CsrfTokenRepository} for the specified
* {@link HttpServletRequest}
*/
public static CsrfTokenRepository getCsrfTokenRepository(HttpServletRequest request) {
CsrfFilter filter = findFilter(request, CsrfFilter.class);
if(filter == null) {
return DEFAULT_TOKEN_REPO;
}
return (CsrfTokenRepository) ReflectionTestUtils.getField(filter, "tokenRepository");
}
/**
* Gets the {@link CsrfTokenRepository} for the specified {@link HttpServletRequest}.
* If one is not found, the default {@link HttpSessionCsrfTokenRepository} is used.
*
* @param request the {@link HttpServletRequest} to obtain the
* {@link CsrfTokenRepository}
* @return the {@link CsrfTokenRepository} for the specified
* {@link HttpServletRequest}
*/
public static CsrfTokenRepository getCsrfTokenRepository(HttpServletRequest request) {
CsrfFilter filter = findFilter(request, CsrfFilter.class);
if (filter == null) {
return DEFAULT_TOKEN_REPO;
}
return (CsrfTokenRepository) ReflectionTestUtils.getField(filter,
"tokenRepository");
}
@SuppressWarnings("unchecked")
private static <T extends Filter> T findFilter(HttpServletRequest request, Class<T> filterClass) {
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
if(webApplicationContext == null) {
return null;
}
FilterChainProxy springSecurityFilterChain = null;
try {
springSecurityFilterChain = webApplicationContext.getBean(FilterChainProxy.class);
} catch(NoSuchBeanDefinitionException notFound) {
return null;
}
List<Filter> filters = (List<Filter>) ReflectionTestUtils.invokeMethod(springSecurityFilterChain,"getFilters", request);
for(Filter filter : filters) {
if(filterClass.isAssignableFrom(filter.getClass())) {
return (T) filter;
}
}
return null;
}
@SuppressWarnings("unchecked")
private static <T extends Filter> T findFilter(HttpServletRequest request,
Class<T> filterClass) {
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getWebApplicationContext(request.getServletContext());
if (webApplicationContext == null) {
return null;
}
FilterChainProxy springSecurityFilterChain = null;
try {
springSecurityFilterChain = webApplicationContext
.getBean(FilterChainProxy.class);
}
catch (NoSuchBeanDefinitionException notFound) {
return null;
}
List<Filter> filters = (List<Filter>) ReflectionTestUtils.invokeMethod(
springSecurityFilterChain, "getFilters", request);
for (Filter filter : filters) {
if (filterClass.isAssignableFrom(filter.getClass())) {
return (T) filter;
}
}
return null;
}
private WebTestUtils() {}
private WebTestUtils() {
}
}
@@ -25,40 +25,40 @@ import org.springframework.security.core.context.SecurityContextHolder;
public class TestSecurityContextHolderTests {
private SecurityContext context;
private SecurityContext context;
@Before
public void setup() {
context = SecurityContextHolder.createEmptyContext();
}
@Before
public void setup() {
context = SecurityContextHolder.createEmptyContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void clearContextClearsBoth() {
SecurityContextHolder.setContext(context);
TestSecurityContextHolder.setContext(context);
@Test
public void clearContextClearsBoth() {
SecurityContextHolder.setContext(context);
TestSecurityContextHolder.setContext(context);
TestSecurityContextHolder.clearContext();
TestSecurityContextHolder.clearContext();
assertThat(SecurityContextHolder.getContext()).isNotSameAs(context);
assertThat(TestSecurityContextHolder.getContext()).isNotSameAs(context);
}
assertThat(SecurityContextHolder.getContext()).isNotSameAs(context);
assertThat(TestSecurityContextHolder.getContext()).isNotSameAs(context);
}
@Test
public void getContextDefaultsNonNull() {
assertThat(TestSecurityContextHolder.getContext()).isNotNull();
assertThat(SecurityContextHolder.getContext()).isNotNull();
}
@Test
public void getContextDefaultsNonNull() {
assertThat(TestSecurityContextHolder.getContext()).isNotNull();
assertThat(SecurityContextHolder.getContext()).isNotNull();
}
@Test
public void setContextSetsBoth() {
TestSecurityContextHolder.setContext(context);
@Test
public void setContextSetsBoth() {
TestSecurityContextHolder.setContext(context);
assertThat(TestSecurityContextHolder.getContext()).isSameAs(context);
assertThat(SecurityContextHolder.getContext()).isSameAs(context);
}
assertThat(TestSecurityContextHolder.getContext()).isSameAs(context);
assertThat(SecurityContextHolder.getContext()).isSameAs(context);
}
}
@@ -65,8 +65,6 @@ public class CustomUserDetails implements UserDetails {
@Override
public String toString() {
return "CustomUserDetails{" +
"username='" + username + '\'' +
'}';
return "CustomUserDetails{" + "username='" + username + '\'' + '}';
}
}
@@ -29,10 +29,10 @@ public @interface WithMockCustomUser {
String username() default "rob";
/**
* The roles to use. The default is "USER". A {@link org.springframework.security.core.GrantedAuthority} will
* be created for each value within roles. Each value in roles will
* automatically be prefixed with "ROLE_". For example, the default will
* result in "ROLE_USER" being used.
* The roles to use. The default is "USER". A
* {@link org.springframework.security.core.GrantedAuthority} will be created for each
* value within roles. Each value in roles will automatically be prefixed with
* "ROLE_". For example, the default will result in "ROLE_USER" being used.
*
* @return
*/
@@ -30,13 +30,15 @@ import java.util.List;
/**
* @author Rob Winch
*/
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
public class WithMockCustomUserSecurityContextFactory implements
WithSecurityContextFactory<WithMockCustomUser> {
public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth =
new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
CustomUserDetails principal = new CustomUserDetails(customUser.name(),
customUser.username());
Authentication auth = new UsernamePasswordAuthenticationToken(principal,
"password", principal.getAuthorities());
context.setAuthentication(auth);
return context;
}
@@ -15,11 +15,12 @@
*/
package org.springframework.security.test.context.showcase;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@@ -29,8 +30,6 @@ import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author Rob Winch
*/
@@ -61,20 +60,23 @@ public class WithMockUserTests {
}
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
public void getMessageWithMockUserCustomUser() {
String message = messageService.getMessage();
assertThat(message).contains("admin").contains("ROLE_USER").contains("ROLE_ADMIN");
assertThat(message).contains("admin").contains("ROLE_USER")
.contains("ROLE_ADMIN");
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = HelloMessageService.class)
static class Config {
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -15,12 +15,13 @@
*/
package org.springframework.security.test.context.showcase;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@@ -34,8 +35,6 @@ import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author Rob Winch
*/
@@ -70,11 +69,13 @@ public class WithUserDetailsTests {
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = HelloMessageService.class)
static class Config {
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService());
}
// @formatter:on
@Bean
public UserDetailsService userDetailsService() {
@@ -88,7 +89,8 @@ public class WithUserDetailsTests {
static class CustomUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
return new CustomUserDetails("name", username);
}
}
@@ -28,7 +28,8 @@ public class HelloMessageService implements MessageService {
@PreAuthorize("authenticated")
public String getMessage() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
return "Hello " + authentication;
}
}
@@ -27,55 +27,60 @@ import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class WithMockUserSecurityContextFactoryTests {
@Mock
private WithMockUser withUser;
@Mock
private WithMockUser withUser;
private WithMockUserSecurityContextFactory factory;
private WithMockUserSecurityContextFactory factory;
@Before
public void setup() {
factory = new WithMockUserSecurityContextFactory();
}
@Before
public void setup() {
factory = new WithMockUserSecurityContextFactory();
}
@Test(expected=IllegalArgumentException.class)
public void usernameNull() {
factory.createSecurityContext(withUser);
}
@Test(expected = IllegalArgumentException.class)
public void usernameNull() {
factory.createSecurityContext(withUser);
}
@Test
public void valueDefaultsUsername() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER"});
@Test
public void valueDefaultsUsername() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER" });
assertThat(factory.createSecurityContext(withUser).getAuthentication().getName()).isEqualTo(withUser.value());
}
assertThat(factory.createSecurityContext(withUser).getAuthentication().getName())
.isEqualTo(withUser.value());
}
@Test
public void usernamePrioritizedOverValue() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.username()).thenReturn("customUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER"});
@Test
public void usernamePrioritizedOverValue() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.username()).thenReturn("customUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER" });
assertThat(factory.createSecurityContext(withUser).getAuthentication().getName()).isEqualTo(withUser.username());
}
assertThat(factory.createSecurityContext(withUser).getAuthentication().getName())
.isEqualTo(withUser.username());
}
@Test
public void rolesWorks() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER", "CUSTOM"});
@Test
public void rolesWorks() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "USER", "CUSTOM" });
assertThat(factory.createSecurityContext(withUser).getAuthentication().getAuthorities()).onProperty("authority").containsOnly("ROLE_USER","ROLE_CUSTOM");
}
assertThat(
factory.createSecurityContext(withUser).getAuthentication()
.getAuthorities()).onProperty("authority").containsOnly(
"ROLE_USER", "ROLE_CUSTOM");
}
@Test(expected = IllegalArgumentException.class)
public void rolesWithRolePrefixFails() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "ROLE_FAIL"});
@Test(expected = IllegalArgumentException.class)
public void rolesWithRolePrefixFails() {
when(withUser.value()).thenReturn("valueUser");
when(withUser.password()).thenReturn("password");
when(withUser.roles()).thenReturn(new String[] { "ROLE_FAIL" });
factory.createSecurityContext(withUser);
}
factory.createSecurityContext(withUser);
}
}
@@ -22,15 +22,17 @@ import org.springframework.core.annotation.AnnotationUtils;
public class WithMockUserTests {
@Test
public void defaults() {
WithMockUser mockUser = AnnotationUtils.findAnnotation(Annotated.class, WithMockUser.class);
assertThat(mockUser.value()).isEqualTo("user");
assertThat(mockUser.username()).isEmpty();
assertThat(mockUser.password()).isEqualTo("password");
assertThat(mockUser.roles()).containsOnly("USER");
}
@Test
public void defaults() {
WithMockUser mockUser = AnnotationUtils.findAnnotation(Annotated.class,
WithMockUser.class);
assertThat(mockUser.value()).isEqualTo("user");
assertThat(mockUser.username()).isEmpty();
assertThat(mockUser.password()).isEqualTo("password");
assertThat(mockUser.roles()).containsOnly("USER");
}
@WithMockUser
private class Annotated {}
@WithMockUser
private class Annotated {
}
}
@@ -32,42 +32,45 @@ import org.springframework.util.ReflectionUtils;
@RunWith(MockitoJUnitRunner.class)
public class WithSecurityContextTestExcecutionListenerTests {
private ConfigurableApplicationContext context;
private ConfigurableApplicationContext context;
@Mock
private TestContext testContext;
@Mock
private TestContext testContext;
private WithSecurityContextTestExecutionListener listener;
private WithSecurityContextTestExecutionListener listener;
@Before
public void setup() {
listener = new WithSecurityContextTestExecutionListener();
context = new AnnotationConfigApplicationContext(Config.class);
}
@Before
public void setup() {
listener = new WithSecurityContextTestExecutionListener();
context = new AnnotationConfigApplicationContext(Config.class);
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
if(context != null) {
context.close();
}
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
if (context != null) {
context.close();
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodNullSecurityContextNoError() throws Exception {
Class testClass = FakeTest.class;
when(testContext.getApplicationContext()).thenReturn(context);
when(testContext.getTestClass()).thenReturn(testClass);
when(testContext.getTestMethod()).thenReturn(ReflectionUtils.findMethod(testClass, "testNoAnnotation"));
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodNullSecurityContextNoError() throws Exception {
Class testClass = FakeTest.class;
when(testContext.getApplicationContext()).thenReturn(context);
when(testContext.getTestClass()).thenReturn(testClass);
when(testContext.getTestMethod()).thenReturn(
ReflectionUtils.findMethod(testClass, "testNoAnnotation"));
listener.beforeTestMethod(testContext);
}
listener.beforeTestMethod(testContext);
}
static class FakeTest {
public void testNoAnnotation() {}
}
static class FakeTest {
public void testNoAnnotation() {
}
}
@Configuration
static class Config {}
@Configuration
static class Config {
}
}
@@ -31,40 +31,41 @@ import org.springframework.security.core.userdetails.UserDetailsService;
@RunWith(MockitoJUnitRunner.class)
public class WithUserDetailsSecurityContextFactoryTests {
@Mock
private UserDetailsService userDetailsService;
@Mock
private UserDetails userDetails;
@Mock
private UserDetailsService userDetailsService;
@Mock
private UserDetails userDetails;
@Mock
private WithUserDetails withUserDetails;
@Mock
private WithUserDetails withUserDetails;
private WithUserDetailsSecurityContextFactory factory;
private WithUserDetailsSecurityContextFactory factory;
@Before
public void setup() {
factory = new WithUserDetailsSecurityContextFactory(userDetailsService);
}
@Before
public void setup() {
factory = new WithUserDetailsSecurityContextFactory(userDetailsService);
}
@Test(expected=IllegalArgumentException.class)
public void createSecurityContextNullValue() {
factory.createSecurityContext(withUserDetails);
}
@Test(expected = IllegalArgumentException.class)
public void createSecurityContextNullValue() {
factory.createSecurityContext(withUserDetails);
}
@Test(expected=IllegalArgumentException.class)
public void createSecurityContextEmptyValue() {
when(withUserDetails.value()).thenReturn("");
factory.createSecurityContext(withUserDetails);
}
@Test(expected = IllegalArgumentException.class)
public void createSecurityContextEmptyValue() {
when(withUserDetails.value()).thenReturn("");
factory.createSecurityContext(withUserDetails);
}
@Test
public void createSecurityContextWithExistingUser() {
String username = "user";
when(withUserDetails.value()).thenReturn(username);
when(userDetailsService.loadUserByUsername(username)).thenReturn(userDetails);
@Test
public void createSecurityContextWithExistingUser() {
String username = "user";
when(withUserDetails.value()).thenReturn(username);
when(userDetailsService.loadUserByUsername(username)).thenReturn(userDetails);
SecurityContext context = factory.createSecurityContext(withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(userDetails);
}
SecurityContext context = factory.createSecurityContext(withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(userDetails);
}
}
@@ -22,12 +22,14 @@ import org.springframework.core.annotation.AnnotationUtils;
public class WithUserDetailsTests {
@Test
public void defaults() {
WithUserDetails userDetails = AnnotationUtils.findAnnotation(Annotated.class, WithUserDetails.class);
assertThat(userDetails.value()).isEqualTo("user");
}
@Test
public void defaults() {
WithUserDetails userDetails = AnnotationUtils.findAnnotation(Annotated.class,
WithUserDetails.class);
assertThat(userDetails.value()).isEqualTo("user");
}
@WithUserDetails
private static class Annotated {}
@WithUserDetails
private static class Annotated {
}
}
@@ -39,53 +39,54 @@ import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.DefaultCsrfToken;
@RunWith(PowerMockRunner.class)
@PrepareForTest({WebTestUtils.class,SecurityMockMvcRequestBuildersFormLoginTests.class})
@PrepareForTest({ WebTestUtils.class, SecurityMockMvcRequestBuildersFormLoginTests.class })
public class SecurityMockMvcRequestBuildersFormLoginTests {
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
private MockServletContext servletContext;
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
private MockServletContext servletContext;
@Before
public void setup() throws Exception {
token = new DefaultCsrfToken("header", "param", "token");
servletContext = new MockServletContext();
mockWebTestUtils();
}
@Before
public void setup() throws Exception {
token = new DefaultCsrfToken("header", "param", "token");
servletContext = new MockServletContext();
mockWebTestUtils();
}
@Test
public void defaults() throws Exception {
MockHttpServletRequest request = formLogin().buildRequest(servletContext);
@Test
public void defaults() throws Exception {
MockHttpServletRequest request = formLogin().buildRequest(servletContext);
assertThat(request.getParameter("username")).isEqualTo("user");
assertThat(request.getParameter("password")).isEqualTo("password");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
assertThat(request.getParameter("username")).isEqualTo("user");
assertThat(request.getParameter("password")).isEqualTo("password");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(
token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void custom() throws Exception {
MockHttpServletRequest request = formLogin("/login").user("username", "admin")
.password("password", "secret").buildRequest(servletContext);
@Test
public void custom() throws Exception {
MockHttpServletRequest request = formLogin("/login")
.user("username","admin")
.password("password","secret")
.buildRequest(servletContext);
assertThat(request.getParameter("username")).isEqualTo("admin");
assertThat(request.getParameter("password")).isEqualTo("secret");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(
token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
assertThat(request.getParameter("username")).isEqualTo("admin");
assertThat(request.getParameter("password")).isEqualTo("secret");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
private void mockWebTestUtils() throws Exception {
spy(WebTestUtils.class);
doReturn(repository).when(WebTestUtils.class,"getCsrfTokenRepository",any(HttpServletRequest.class));
when(repository.generateToken(any(HttpServletRequest.class))).thenReturn(token);
}
private void mockWebTestUtils() throws Exception {
spy(WebTestUtils.class);
doReturn(repository).when(WebTestUtils.class, "getCsrfTokenRepository",
any(HttpServletRequest.class));
when(repository.generateToken(any(HttpServletRequest.class))).thenReturn(token);
}
}
@@ -39,46 +39,51 @@ import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.DefaultCsrfToken;
@RunWith(PowerMockRunner.class)
@PrepareForTest({WebTestUtils.class,SecurityMockMvcRequestBuildersFormLogoutTests.class})
@PrepareForTest({ WebTestUtils.class, SecurityMockMvcRequestBuildersFormLogoutTests.class })
public class SecurityMockMvcRequestBuildersFormLogoutTests {
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
private MockServletContext servletContext;
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
private MockServletContext servletContext;
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
servletContext = new MockServletContext();
}
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
servletContext = new MockServletContext();
}
@Test
public void defaults() throws Exception {
mockWebTestUtils();
MockHttpServletRequest request = logout().buildRequest(servletContext);
@Test
public void defaults() throws Exception {
mockWebTestUtils();
MockHttpServletRequest request = logout().buildRequest(servletContext);
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/logout");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(
token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/logout");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void custom() throws Exception {
mockWebTestUtils();
MockHttpServletRequest request = logout("/admin/logout").buildRequest(servletContext);
@Test
public void custom() throws Exception {
mockWebTestUtils();
MockHttpServletRequest request = logout("/admin/logout").buildRequest(
servletContext);
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/admin/logout");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(
token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/admin/logout");
verify(repository).saveToken(eq(token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
private void mockWebTestUtils() throws Exception {
spy(WebTestUtils.class);
doReturn(repository).when(WebTestUtils.class,"getCsrfTokenRepository",any(HttpServletRequest.class));
when(repository.generateToken(any(HttpServletRequest.class))).thenReturn(token);
}
private void mockWebTestUtils() throws Exception {
spy(WebTestUtils.class);
doReturn(repository).when(WebTestUtils.class, "getCsrfTokenRepository",
any(HttpServletRequest.class));
when(repository.generateToken(any(HttpServletRequest.class))).thenReturn(token);
}
}
@@ -41,65 +41,62 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.Config.class)
@ContextConfiguration(classes = SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.Config.class)
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
// SEC-2593
@Test
public void userRequestPostProcessorWorksWithStateless() throws Exception {
mvc
.perform(get("/").with(user("user")))
.andExpect(status().is2xxSuccessful());
}
// SEC-2593
@Test
public void userRequestPostProcessorWorksWithStateless() throws Exception {
mvc.perform(get("/").with(user("user"))).andExpect(status().is2xxSuccessful());
}
// SEC-2593
@WithMockUser
@Test
public void withMockUserWorksWithStateless() throws Exception {
mvc
.perform(get("/"))
.andExpect(status().is2xxSuccessful());
}
// SEC-2593
@WithMockUser
@Test
public void withMockUserWorksWithStateless() throws Exception {
mvc.perform(get("/")).andExpect(status().is2xxSuccessful());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication();
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication();
}
// @formatter:on
@RestController
static class Controller {
@RequestMapping
public String hello() {
return "Hello";
}
}
}
@RestController
static class Controller {
@RequestMapping
public String hello() {
return "Hello";
}
}
}
}
@@ -44,38 +44,39 @@ import org.springframework.security.web.context.SecurityContextRepository;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Mock
private Authentication authentication;
@Mock
private Authentication authentication;
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
authentication(authentication).postProcessRequest(request);
@Test
public void userDetails() {
authentication(authentication).postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isSameAs(authentication);
}
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isSameAs(authentication);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
}
@@ -29,32 +29,37 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock
@RunWith(MockitoJUnitRunner.class)
public class SecurityMockMvcRequestPostProcessorsCertificateTests {
@Mock
private X509Certificate certificate;
@Mock
private X509Certificate certificate;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Before
public void setup() {
request = new MockHttpServletRequest();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
}
@Test
public void x509SingleCertificate() {
MockHttpServletRequest postProcessedRequest = x509(certificate).postProcessRequest(request);
@Test
public void x509SingleCertificate() {
MockHttpServletRequest postProcessedRequest = x509(certificate)
.postProcessRequest(request);
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest.getAttribute("javax.servlet.request.X509Certificate");
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
.getAttribute("javax.servlet.request.X509Certificate");
assertThat(certificates).containsOnly(certificate);
}
assertThat(certificates).containsOnly(certificate);
}
@Test
public void x509ResourceName() throws Exception {
MockHttpServletRequest postProcessedRequest = x509("rod.cer").postProcessRequest(request);
@Test
public void x509ResourceName() throws Exception {
MockHttpServletRequest postProcessedRequest = x509("rod.cer").postProcessRequest(
request);
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest.getAttribute("javax.servlet.request.X509Certificate");
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
.getAttribute("javax.servlet.request.X509Certificate");
assertThat(certificates.length).isEqualTo(1);
assertThat(certificates[0].getSubjectDN().getName()).isEqualTo("CN=rod, OU=Spring Security, O=Spring Framework");
}
assertThat(certificates.length).isEqualTo(1);
assertThat(certificates[0].getSubjectDN().getName()).isEqualTo(
"CN=rod, OU=Spring Security, O=Spring Framework");
}
}
@@ -33,55 +33,62 @@ import org.springframework.security.web.csrf.DefaultCsrfToken;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsCsrfTests {
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
@Mock
private CsrfTokenRepository repository;
private DefaultCsrfToken token;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Test
public void csrfWithParam() {
MockHttpServletRequest postProcessedRequest = csrf().postProcessRequest(request);
@Test
public void csrfWithParam() {
MockHttpServletRequest postProcessedRequest = csrf().postProcessRequest(request);
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNull();
}
assertThat(postProcessedRequest.getParameter(token.getParameterName()))
.isEqualTo(token.getToken());
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNull();
}
@Test
public void csrfWithHeader() {
MockHttpServletRequest postProcessedRequest = csrf().asHeader().postProcessRequest(request);
@Test
public void csrfWithHeader() {
MockHttpServletRequest postProcessedRequest = csrf().asHeader()
.postProcessRequest(request);
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isNull();
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isEqualTo(token.getToken());
}
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isNull();
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isEqualTo(
token.getToken());
}
@Test
public void csrfWithInvalidParam() {
MockHttpServletRequest postProcessedRequest = csrf().useInvalidToken().postProcessRequest(request);
@Test
public void csrfWithInvalidParam() {
MockHttpServletRequest postProcessedRequest = csrf().useInvalidToken()
.postProcessRequest(request);
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isNotEmpty().isNotEqualTo(token.getToken());
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNull();
}
assertThat(postProcessedRequest.getParameter(token.getParameterName()))
.isNotEmpty().isNotEqualTo(token.getToken());
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNull();
}
@Test
public void csrfWithInvalidHeader() {
MockHttpServletRequest postProcessedRequest = csrf().asHeader().useInvalidToken().postProcessRequest(request);
@Test
public void csrfWithInvalidHeader() {
MockHttpServletRequest postProcessedRequest = csrf().asHeader().useInvalidToken()
.postProcessRequest(request);
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isNull();
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNotEmpty().isNotEqualTo(token.getToken());
}
assertThat(postProcessedRequest.getParameter(token.getParameterName())).isNull();
assertThat(postProcessedRequest.getHeader(token.getHeaderName())).isNotEmpty()
.isNotEqualTo(token.getToken());
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getCsrfTokenRepository(request)).thenReturn(repository);
when(repository.loadToken(request)).thenReturn(token);
when(repository.generateToken(request)).thenReturn(token);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getCsrfTokenRepository(request)).thenReturn(repository);
when(repository.loadToken(request)).thenReturn(token);
when(repository.generateToken(request)).thenReturn(token);
}
}
@@ -41,87 +41,96 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock
public class SecurityMockMvcRequestPostProcessorsDigestTests {
private DigestAuthenticationFilter filter;
private MockHttpServletRequest request;
private DigestAuthenticationFilter filter;
private MockHttpServletRequest request;
private String username;
private String username;
private String password;
private String password;
private DigestAuthenticationEntryPoint entryPoint;
private DigestAuthenticationEntryPoint entryPoint;
@Before
public void setup() {
this.password = "password";
request = new MockHttpServletRequest();
@Before
public void setup() {
this.password = "password";
request = new MockHttpServletRequest();
entryPoint = new DigestAuthenticationEntryPoint();
entryPoint.setKey("key");
entryPoint.setRealmName("Spring Security");
filter = new DigestAuthenticationFilter();
filter.setUserDetailsService(new UserDetailsService() {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return new User(username,password, AuthorityUtils.createAuthorityList("ROLE_USER"));
}
});
filter.setAuthenticationEntryPoint(entryPoint);
filter.afterPropertiesSet();
}
entryPoint = new DigestAuthenticationEntryPoint();
entryPoint.setKey("key");
entryPoint.setRealmName("Spring Security");
filter = new DigestAuthenticationFilter();
filter.setUserDetailsService(new UserDetailsService() {
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
return new User(username, password, AuthorityUtils
.createAuthorityList("ROLE_USER"));
}
});
filter.setAuthenticationEntryPoint(entryPoint);
filter.afterPropertiesSet();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void digestWithFilter() throws Exception {
MockHttpServletRequest postProcessedRequest = digest().postProcessRequest(request);
@Test
public void digestWithFilter() throws Exception {
MockHttpServletRequest postProcessedRequest = digest()
.postProcessRequest(request);
assertThat(extractUser()).isEqualTo("user");
}
assertThat(extractUser()).isEqualTo("user");
}
@Test
public void digestWithFilterCustomUsername() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username).postProcessRequest(request);
@Test
public void digestWithFilterCustomUsername() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username)
.postProcessRequest(request);
assertThat(extractUser()).isEqualTo(username);
}
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterCustomPassword() throws Exception {
String username = "custom";
password = "secret";
MockHttpServletRequest postProcessedRequest = digest(username).password(password).postProcessRequest(request);
@Test
public void digestWithFilterCustomPassword() throws Exception {
String username = "custom";
password = "secret";
MockHttpServletRequest postProcessedRequest = digest(username).password(password)
.postProcessRequest(request);
assertThat(extractUser()).isEqualTo(username);
}
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterCustomRealm() throws Exception {
String username = "admin";
entryPoint.setRealmName("Custom");
MockHttpServletRequest postProcessedRequest = digest(username).realm(entryPoint.getRealmName()).postProcessRequest(request);
@Test
public void digestWithFilterCustomRealm() throws Exception {
String username = "admin";
entryPoint.setRealmName("Custom");
MockHttpServletRequest postProcessedRequest = digest(username).realm(
entryPoint.getRealmName()).postProcessRequest(request);
assertThat(extractUser()).isEqualTo(username);
}
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterFails() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username).realm("Invalid").postProcessRequest(request);
@Test
public void digestWithFilterFails() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username).realm("Invalid")
.postProcessRequest(request);
assertThat(extractUser()).isNull();
}
assertThat(extractUser()).isNull();
}
private String extractUser() throws IOException, ServletException {
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
username = authentication == null ? null : authentication.getName();
}
});
return username;
}
private String extractUser() throws IOException, ServletException {
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
username = authentication == null ? null : authentication.getName();
}
});
return username;
}
}
@@ -43,38 +43,39 @@ import org.springframework.security.web.context.SecurityContextRepository;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Mock
private SecurityContext expectedContext;
@Mock
private SecurityContext expectedContext;
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
securityContext(expectedContext).postProcessRequest(request);
@Test
public void userDetails() {
securityContext(expectedContext).postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context).isSameAs(this.expectedContext);
}
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context).isSameAs(this.expectedContext);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
}
@@ -48,56 +48,56 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/").with(testSecurityContext()))
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/").with(testSecurityContext())).build();
}
@Test
@WithMockUser
public void testSecurityContextWithMockUserWorksWithStateless() throws Exception {
mvc
.perform(get("/"))
.andExpect(status().is2xxSuccessful());
}
@Test
@WithMockUser
public void testSecurityContextWithMockUserWorksWithStateless() throws Exception {
mvc.perform(get("/")).andExpect(status().is2xxSuccessful());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication();
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication();
}
// @formatter:on
@RestController
static class Controller {
@RequestMapping
public String hello() {
return "Hello";
}
}
}
@RestController
static class Controller {
@RequestMapping
public String hello() {
return "Hello";
}
}
}
}
@@ -39,43 +39,45 @@ import org.springframework.security.web.context.SecurityContextRepository;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
@Mock
private SecurityContext context;
@Mock
private SecurityContextRepository repository;
@Mock
private SecurityContext context;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void testSecurityContextSaves() {
TestSecurityContextHolder.setContext(context);
@Test
public void testSecurityContextSaves() {
TestSecurityContextHolder.setContext(context);
testSecurityContext().postProcessRequest(request);
testSecurityContext().postProcessRequest(request);
verify(repository).saveContext(eq(context), eq(request), any(HttpServletResponse.class));
}
verify(repository).saveContext(eq(context), eq(request),
any(HttpServletResponse.class));
}
// Ensure it does not fail if TestSecurityContextHolder is not initialized
@Test
public void testSecurityContextNoContext() {
testSecurityContext().postProcessRequest(request);
// Ensure it does not fail if TestSecurityContextHolder is not initialized
@Test
public void testSecurityContextNoContext() {
testSecurityContext().postProcessRequest(request);
verify(repository).saveContext(any(SecurityContext.class), eq(request), any(HttpServletResponse.class));
}
verify(repository).saveContext(any(SecurityContext.class), eq(request),
any(HttpServletResponse.class));
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
}
@@ -45,39 +45,41 @@ import org.springframework.security.web.context.SecurityContextRepository;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Mock
private UserDetails userDetails;
@Mock
private UserDetails userDetails;
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
user(userDetails).postProcessRequest(request);
@Test
public void userDetails() {
user(userDetails).postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isSameAs(userDetails);
}
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isSameAs(userDetails);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
}
@@ -47,96 +47,98 @@ import org.springframework.security.web.context.SecurityContextRepository;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
public class SecurityMockMvcRequestPostProcessorsUserTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
private MockHttpServletRequest request;
@Mock
private GrantedAuthority authority1;
@Mock
private GrantedAuthority authority2;
@Mock
private GrantedAuthority authority1;
@Mock
private GrantedAuthority authority2;
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
mockWebTestUtils();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@After
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userWithDefaults() {
String username = "userabc";
@Test
public void userWithDefaults() {
String username = "userabc";
user(username).postProcessRequest(request);
user(username).postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("password");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority").containsOnly("ROLE_USER");
}
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("password");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority")
.containsOnly("ROLE_USER");
}
@Test
public void userWithCustom() {
String username = "customuser";
@Test
public void userWithCustom() {
String username = "customuser";
user(username).roles("CUSTOM", "ADMIN").password("newpass")
.postProcessRequest(request);
user(username)
.roles("CUSTOM","ADMIN")
.password("newpass")
.postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority")
.containsOnly("ROLE_CUSTOM", "ROLE_ADMIN");
}
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority").containsOnly("ROLE_CUSTOM","ROLE_ADMIN");
}
@Test
public void userCustomAuthoritiesVarargs() {
String username = "customuser";
@Test
public void userCustomAuthoritiesVarargs() {
String username = "customuser";
user(username).authorities(authority1, authority2).postProcessRequest(request);
user(username)
.authorities(authority1,authority2)
.postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication().getAuthorities()).containsOnly(authority1,
authority2);
}
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication().getAuthorities()).containsOnly(authority1,authority2);
}
@Test(expected = IllegalArgumentException.class)
public void userRolesWithRolePrefixErrors() {
user("user").roles("ROLE_INVALID").postProcessRequest(request);
}
@Test(expected = IllegalArgumentException.class)
public void userRolesWithRolePrefixErrors() {
user("user")
.roles("ROLE_INVALID")
.postProcessRequest(request);
}
@Test
public void userCustomAuthoritiesList() {
String username = "customuser";
@Test
public void userCustomAuthoritiesList() {
String username = "customuser";
user(username).authorities(Arrays.asList(authority1, authority2))
.postProcessRequest(request);
user(username)
.authorities(Arrays.asList(authority1,authority2))
.postProcessRequest(request);
verify(repository).saveContext(contextCaptor.capture(), eq(request),
any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication().getAuthorities()).containsOnly(authority1,
authority2);
}
verify(repository).saveContext(contextCaptor.capture(), eq(request), any(HttpServletResponse.class));
SecurityContext context = contextCaptor.getValue();
assertThat(context.getAuthentication().getAuthorities()).containsOnly(authority1,authority2);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
private void mockWebTestUtils() {
spy(WebTestUtils.class);
when(WebTestUtils.getSecurityContextRepository(request)).thenReturn(repository);
}
}
@@ -8,10 +8,9 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@@ -26,49 +25,49 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@ContextConfiguration(classes = SecurityMockMvcResultMatchersTests.Config.class)
@WebAppConfiguration
public class SecurityMockMvcResultMatchersTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity())
.build();
}
// SEC-2719
@Test
public void withRolesNotOrderSensitive() throws Exception {
mockMvc.perform(formLogin())
.andExpect(authenticated().withRoles("USER","SELLER"))
.andExpect(authenticated().withRoles("SELLER","USER"));
}
// SEC-2719
@Test
public void withRolesNotOrderSensitive() throws Exception {
mockMvc.perform(formLogin())
.andExpect(authenticated().withRoles("USER", "SELLER"))
.andExpect(authenticated().withRoles("SELLER", "USER"));
}
@Test(expected = AssertionError.class)
public void withRolesFailsIfNotAllRoles() throws Exception {
mockMvc.perform(formLogin())
.andExpect(authenticated().withRoles("USER"));
}
@Test(expected = AssertionError.class)
public void withRolesFailsIfNotAllRoles() throws Exception {
mockMvc.perform(formLogin()).andExpect(authenticated().withRoles("USER"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").roles("USER","SELLER").password("password");
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").roles("USER","SELLER").password("password");
}
// @formatter:on
@RestController
static class Controller {
@RequestMapping("/")
public String ok() {
return "ok";
}
}
}
@RestController
static class Controller {
@RequestMapping("/")
public String ok() {
return "ok";
}
}
}
}
@@ -31,54 +31,53 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SecurityMockMvcConfigurerTests {
@Mock
private Filter filter;
@Mock
private Filter beanFilter;
@Mock
private ConfigurableMockMvcBuilder builder;
@Mock
private WebApplicationContext context;
@Mock
private Filter filter;
@Mock
private Filter beanFilter;
@Mock
private ConfigurableMockMvcBuilder builder;
@Mock
private WebApplicationContext context;
@Test
public void beforeMockMvcCreatedOverrideBean() throws Exception {
returnFilterBean();
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(filter);
@Test
public void beforeMockMvcCreatedOverrideBean() throws Exception {
returnFilterBean();
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(filter);
configurer.beforeMockMvcCreated(builder, context);
configurer.beforeMockMvcCreated(builder, context);
verify(builder).addFilters(filter);
}
verify(builder).addFilters(filter);
}
@Test
public void beforeMockMvcCreatedBean() throws Exception {
returnFilterBean();
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
@Test
public void beforeMockMvcCreatedBean() throws Exception {
returnFilterBean();
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
configurer.beforeMockMvcCreated(builder, context);
configurer.beforeMockMvcCreated(builder, context);
verify(builder).addFilters(beanFilter);
}
verify(builder).addFilters(beanFilter);
}
@Test
public void beforeMockMvcCreatedNoBean() throws Exception {
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(filter);
@Test
public void beforeMockMvcCreatedNoBean() throws Exception {
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(filter);
configurer.beforeMockMvcCreated(builder, context);
configurer.beforeMockMvcCreated(builder, context);
verify(builder).addFilters(filter);
}
verify(builder).addFilters(filter);
}
@Test(expected = IllegalStateException.class)
public void beforeMockMvcCreatedNoFilter() throws Exception {
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
@Test(expected = IllegalStateException.class)
public void beforeMockMvcCreatedNoFilter() throws Exception {
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
configurer.beforeMockMvcCreated(builder, context);
}
configurer.beforeMockMvcCreated(builder, context);
}
private void returnFilterBean() {
when(context.containsBean(anyString())).thenReturn(true);
when(context.getBean(anyString(),eq(Filter.class))).thenReturn(beanFilter);
}
private void returnFilterBean() {
when(context.containsBean(anyString())).thenReturn(true);
when(context.getBean(anyString(), eq(Filter.class))).thenReturn(beanFilter);
}
}
@@ -15,15 +15,20 @@
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@@ -32,64 +37,51 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CsrfShowcaseTests.Config.class)
@ContextConfiguration(classes = CsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class CsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc
.perform(post("/").with(csrf()))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc.perform(post("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc
.perform(put("/").with(csrf()))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc.perform(put("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithNoCsrfForbidden() throws Exception {
mvc
.perform(post("/"))
.andExpect(status().isForbidden());
}
@Test
public void postWithNoCsrfForbidden() throws Exception {
mvc.perform(post("/")).andExpect(status().isForbidden());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -14,21 +14,23 @@
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ContextConfiguration;
@@ -40,64 +42,61 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CustomCsrfShowcaseTests.Config.class)
@ContextConfiguration(classes = CustomCsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class CustomCsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private CsrfTokenRepository repository;
@Autowired
private CsrfTokenRepository repository;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/").with(csrf()))
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.defaultRequest(get("/").with(csrf())).apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc
.perform(post("/").with(csrf()))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc.perform(post("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc
.perform(put("/").with(csrf()))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc.perform(put("/").with(csrf())).andExpect(status().isNotFound());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(repo());
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(repo());
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
@Bean
public CsrfTokenRepository repo() {
HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
repo.setParameterName("custom_csrf");
return repo;
}
}
@Bean
public CsrfTokenRepository repo() {
HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
repo.setParameterName("custom_csrf");
return repo;
}
}
}
@@ -14,6 +14,7 @@
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@@ -37,51 +38,46 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DefaultCsrfShowcaseTests.Config.class)
@ContextConfiguration(classes = DefaultCsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class DefaultCsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/").with(csrf()))
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.defaultRequest(get("/").with(csrf())).apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc
.perform(post("/"))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorks() throws Exception {
mvc.perform(post("/")).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc
.perform(put("/"))
.andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
mvc.perform(put("/")).andExpect(status().isNotFound());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -39,64 +39,56 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AuthenticationTests.Config.class)
@ContextConfiguration(classes = AuthenticationTests.Config.class)
@WebAppConfiguration
public class AuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void requiresAuthentication() throws Exception {
mvc
.perform(get("/"))
.andExpect(status().isMovedTemporarily());
}
@Test
public void requiresAuthentication() throws Exception {
mvc.perform(get("/")).andExpect(status().isMovedTemporarily());
}
@Test
public void httpBasicAuthenticationSuccess() throws Exception {
mvc
.perform(get("/secured/butnotfound").with(httpBasic("user","password")))
.andExpect(status().isNotFound())
.andExpect(authenticated().withUsername("user"));
}
@Test
public void httpBasicAuthenticationSuccess() throws Exception {
mvc.perform(get("/secured/butnotfound").with(httpBasic("user", "password")))
.andExpect(status().isNotFound())
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationSuccess() throws Exception {
mvc
.perform(formLogin())
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationSuccess() throws Exception {
mvc.perform(formLogin()).andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
mvc
.perform(formLogin().user("user").password("invalid"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/login?error"))
.andExpect(unauthenticated());
}
@Test
public void authenticationFailed() throws Exception {
mvc.perform(formLogin().user("user").password("invalid"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/login?error")).andExpect(unauthenticated());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -43,84 +43,82 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CustomConfigAuthenticationTests.Config.class)
@ContextConfiguration(classes = CustomConfigAuthenticationTests.Config.class)
@WebAppConfiguration
public class CustomConfigAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private SecurityContextRepository securityContextRepository;
@Autowired
private SecurityContextRepository securityContextRepository;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void authenticationSuccess() throws Exception {
mvc
.perform(formLogin("/authenticate").user("user","user").password("pass","password"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationSuccess() throws Exception {
mvc.perform(
formLogin("/authenticate").user("user", "user").password("pass",
"password")).andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void withUserSuccess() throws Exception {
mvc.perform(get("/").with(user("user"))).andExpect(status().isNotFound())
.andExpect(authenticated().withUsername("user"));
}
@Test
public void withUserSuccess() throws Exception {
mvc
.perform(get("/").with(user("user")))
.andExpect(status().isNotFound())
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
mvc.perform(
formLogin("/authenticate").user("user", "notfound").password("pass",
"invalid")).andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/authenticate?error"))
.andExpect(unauthenticated());
}
@Test
public void authenticationFailed() throws Exception {
mvc
.perform(formLogin("/authenticate").user("user","notfound").password("pass","invalid"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/authenticate?error"))
.andExpect(unauthenticated());
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.securityContext()
.securityContextRepository(securityContextRepository())
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
}
// @formatter:on
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.securityContext()
.securityContextRepository(securityContextRepository())
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Bean
public SecurityContextRepository securityContextRepository() {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("CUSTOM");
return repo;
}
}
@Bean
public SecurityContextRepository securityContextRepository() {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("CUSTOM");
return repo;
}
}
}
@@ -39,69 +39,65 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CustomLoginRequestBuilderAuthenticationTests.Config.class)
@ContextConfiguration(classes = CustomLoginRequestBuilderAuthenticationTests.Config.class)
@WebAppConfiguration
public class CustomLoginRequestBuilderAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void authenticationSuccess() throws Exception {
mvc
.perform(login())
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationSuccess() throws Exception {
mvc.perform(login()).andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
mvc
.perform(login().user("notfound").password("invalid"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/authenticate?error"))
.andExpect(unauthenticated());
}
@Test
public void authenticationFailed() throws Exception {
mvc.perform(login().user("notfound").password("invalid"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/authenticate?error"))
.andExpect(unauthenticated());
}
static FormLoginRequestBuilder login() {
return SecurityMockMvcRequestBuilders
.formLogin("/authenticate")
.userParameter("user")
.passwordParam("pass");
}
static FormLoginRequestBuilder login() {
return SecurityMockMvcRequestBuilders.formLogin("/authenticate")
.userParameter("user").passwordParam("pass");
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -41,66 +41,66 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DefaultfSecurityRequestsTests.Config.class)
@ContextConfiguration(classes = DefaultfSecurityRequestsTests.Config.class)
@WebAppConfiguration
public class DefaultfSecurityRequestsTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/").with(user("user").roles("ADMIN")))
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.defaultRequest(get("/").with(user("user").roles("ADMIN")))
.apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -44,93 +44,91 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SecurityRequestsTests.Config.class)
@ContextConfiguration(classes = SecurityRequestsTests.Config.class)
@WebAppConfiguration
public class SecurityRequestsTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserDetailsService userDetailsService;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/").with(user("user")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc.perform(get("/").with(user("user")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin").with(user("admin").roles("ADMIN")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with admin
.andExpect(authenticated().withUsername("admin"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with admin
.andExpect(authenticated().withUsername("admin"));
}
@Test
public void requestProtectedUrlWithUserDetails() throws Exception {
UserDetails user = userDetailsService.loadUserByUsername("user");
mvc
.perform(get("/").with(user(user)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthenticationPrincipal(user));
}
@Test
public void requestProtectedUrlWithUserDetails() throws Exception {
UserDetails user = userDetailsService.loadUserByUsername("user");
mvc.perform(get("/").with(user(user)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthenticationPrincipal(user));
}
@Test
public void requestProtectedUrlWithAuthentication() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "notused", "ROLE_USER");
mvc
.perform(get("/").with(authentication(authentication)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthentication(authentication));
}
@Test
public void requestProtectedUrlWithAuthentication() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "notused",
"ROLE_USER");
mvc.perform(get("/").with(authentication(authentication)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthentication(authentication));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
}
@@ -39,64 +39,64 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WithUserAuthenticationTests.Config.class)
@ContextConfiguration(classes = WithUserAuthenticationTests.Config.class)
@WebAppConfiguration
public class WithUserAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity()).build();
}
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@Test
@WithMockUser(roles = "ADMIN")
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -39,63 +39,62 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WithUserClassLevelAuthenticationTests.Config.class)
@ContextConfiguration(classes = WithUserClassLevelAuthenticationTests.Config.class)
@WebAppConfiguration
@WithMockUser(roles="ADMIN")
@WithMockUser(roles = "ADMIN")
public class WithUserClassLevelAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// @formatter:on
}
}
@@ -41,71 +41,71 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WithUserDetailsAuthenticationTests.Config.class)
@ContextConfiguration(classes = WithUserDetailsAuthenticationTests.Config.class)
@WebAppConfiguration
public class WithUserDetailsAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
@WithUserDetails
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithUserDetails
public void requestProtectedUrlWithUser() throws Exception {
mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithUserDetails("admin")
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN","USER"));
}
@Test
@WithUserDetails("admin")
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(
authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER","ADMIN");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER","ADMIN");
}
// @formatter:on
}
}
@@ -41,70 +41,71 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WithUserDetailsClassLevelAuthenticationTests.Config.class)
@ContextConfiguration(classes = WithUserDetailsClassLevelAuthenticationTests.Config.class)
@WebAppConfiguration
@WithUserDetails("admin")
public class WithUserDetailsClassLevelAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
public void requestRootUrlWithAdmin() throws Exception {
mvc
.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN","USER"));
}
@Test
public void requestRootUrlWithAdmin() throws Exception {
mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(
authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN","USER"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(
authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
// @formatter:on
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER","ADMIN");
}
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER","ADMIN");
}
// @formatter:on
}
}
@@ -40,111 +40,121 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
@RunWith(MockitoJUnitRunner.class)
public class WebTestUtilsTests {
@Mock
private SecurityContextRepository contextRepo;
@Mock
private CsrfTokenRepository csrfRepo;
@Mock
private SecurityContextRepository contextRepo;
@Mock
private CsrfTokenRepository csrfRepo;
private MockHttpServletRequest request;
private ConfigurableApplicationContext context;
private MockHttpServletRequest request;
private ConfigurableApplicationContext context;
@Before
public void setup() {
request = new MockHttpServletRequest();
}
@Before
public void setup() {
request = new MockHttpServletRequest();
}
@After
public void cleanup() {
if(context != null) {
context.close();
}
}
@After
public void cleanup() {
if (context != null) {
context.close();
}
}
@Test
public void getCsrfTokenRepositorytNoWac() {
assertThat(getCsrfTokenRepository(request)).isInstanceOf(HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytNoWac() {
assertThat(getCsrfTokenRepository(request)).isInstanceOf(
HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytNoSecurity() {
loadConfig(Config.class);
assertThat(getCsrfTokenRepository(request)).isInstanceOf(HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytNoSecurity() {
loadConfig(Config.class);
assertThat(getCsrfTokenRepository(request)).isInstanceOf(
HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytSecurityNoCsrf() {
loadConfig(SecurityNoCsrfConfig.class);
assertThat(getCsrfTokenRepository(request)).isInstanceOf(HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytSecurityNoCsrf() {
loadConfig(SecurityNoCsrfConfig.class);
assertThat(getCsrfTokenRepository(request)).isInstanceOf(
HttpSessionCsrfTokenRepository.class);
}
@Test
public void getCsrfTokenRepositorytSecurityCustomRepo() {
CustomSecurityConfig.CONTEXT_REPO = contextRepo;
CustomSecurityConfig.CSRF_REPO = csrfRepo;
loadConfig(CustomSecurityConfig.class);
assertThat(getCsrfTokenRepository(request)).isSameAs(csrfRepo);
}
@Test
public void getCsrfTokenRepositorytSecurityCustomRepo() {
CustomSecurityConfig.CONTEXT_REPO = contextRepo;
CustomSecurityConfig.CSRF_REPO = csrfRepo;
loadConfig(CustomSecurityConfig.class);
assertThat(getCsrfTokenRepository(request)).isSameAs(csrfRepo);
}
// getSecurityContextRepository
// getSecurityContextRepository
@Test
public void getSecurityContextRepositoryNoWac() {
assertThat(getSecurityContextRepository(request)).isInstanceOf(HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositoryNoWac() {
assertThat(getSecurityContextRepository(request)).isInstanceOf(
HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositoryNoSecurity() {
loadConfig(Config.class);
assertThat(getSecurityContextRepository(request)).isInstanceOf(HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositoryNoSecurity() {
loadConfig(Config.class);
assertThat(getSecurityContextRepository(request)).isInstanceOf(
HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositorySecurityNoCsrf() {
loadConfig(SecurityNoCsrfConfig.class);
assertThat(getSecurityContextRepository(request)).isInstanceOf(HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositorySecurityNoCsrf() {
loadConfig(SecurityNoCsrfConfig.class);
assertThat(getSecurityContextRepository(request)).isInstanceOf(
HttpSessionSecurityContextRepository.class);
}
@Test
public void getSecurityContextRepositorySecurityCustomRepo() {
CustomSecurityConfig.CONTEXT_REPO = contextRepo;
CustomSecurityConfig.CSRF_REPO = csrfRepo;
loadConfig(CustomSecurityConfig.class);
assertThat(getSecurityContextRepository(request)).isSameAs(contextRepo);
}
@Test
public void getSecurityContextRepositorySecurityCustomRepo() {
CustomSecurityConfig.CONTEXT_REPO = contextRepo;
CustomSecurityConfig.CSRF_REPO = csrfRepo;
loadConfig(CustomSecurityConfig.class);
assertThat(getSecurityContextRepository(request)).isSameAs(contextRepo);
}
private void loadConfig(Class<?> config) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(config);
context.refresh();
this.context = context;
request.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
}
private void loadConfig(Class<?> config) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(config);
context.refresh();
this.context = context;
request.getServletContext().setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
}
@Configuration
static class Config {}
@Configuration
static class Config {
}
@EnableWebSecurity
static class SecurityNoCsrfConfig extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
static class SecurityNoCsrfConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
@EnableWebSecurity
static class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
static CsrfTokenRepository CSRF_REPO;
static SecurityContextRepository CONTEXT_REPO;
@EnableWebSecurity
static class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
static CsrfTokenRepository CSRF_REPO;
static SecurityContextRepository CONTEXT_REPO;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CSRF_REPO)
.and()
.securityContext()
.securityContextRepository(CONTEXT_REPO);
}
}
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CSRF_REPO)
.and()
.securityContext()
.securityContextRepository(CONTEXT_REPO);
}
// @formatter:on
}
}