Skip to content

Fix unauthenitcated() and AnonymousAuthenticationToken #3818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@
*/
package org.springframework.security.test.web.servlet.response;

import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
Expand All @@ -32,6 +31,9 @@
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;

import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;

/**
* Security related {@link MockMvc} {@link ResultMatcher}s.
*
Expand Down Expand Up @@ -78,15 +80,16 @@ protected SecurityContext load(MvcResult result) {
* @author Rob Winch
* @since 4.0
*/
public static final class AuthenticatedMatcher extends
AuthenticationMatcher<AuthenticatedMatcher> {
public static final class AuthenticatedMatcher
extends AuthenticationMatcher<AuthenticatedMatcher> {

private SecurityContext expectedContext;
private Authentication expectedAuthentication;
private Object expectedAuthenticationPrincipal;
private String expectedAuthenticationName;
private Collection<? extends GrantedAuthority> expectedGrantedAuthorities;

@Override
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);

Expand All @@ -109,10 +112,11 @@ public void match(MvcResult result) throws Exception {
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());
assertEquals(
this.expectedAuthenticationPrincipal + " does not equal "
+ context.getAuthentication().getPrincipal(),
this.expectedAuthenticationPrincipal,
context.getAuthentication().getPrincipal());
}

if (this.expectedAuthenticationName != null) {
Expand All @@ -126,8 +130,9 @@ public void match(MvcResult result) throws Exception {
assertTrue("Authentication cannot be null", auth != null);
Collection<? extends GrantedAuthority> authorities = auth
.getAuthorities();
assertTrue(authorities + " does not contain the same authorities as "
+ this.expectedGrantedAuthorities,
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,
Expand Down Expand Up @@ -195,7 +200,8 @@ public AuthenticatedMatcher withAuthenticationName(String expected) {
* @param expected the {@link Authentication#getAuthorities()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthorities(Collection<? extends GrantedAuthority> expected) {
public AuthenticatedMatcher withAuthorities(
Collection<? extends GrantedAuthority> expected) {
this.expectedGrantedAuthorities = expected;
return this;
}
Expand Down Expand Up @@ -225,13 +231,18 @@ public AuthenticatedMatcher withRoles(String... roles) {
* @author Rob Winch
* @since 4.0
*/
private static final class UnAuthenticatedMatcher extends
AuthenticationMatcher<UnAuthenticatedMatcher> {
private static final class UnAuthenticatedMatcher
extends AuthenticationMatcher<UnAuthenticatedMatcher> {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();

@Override
public void match(MvcResult result) throws Exception {
SecurityContext context = load(result);

assertEquals("", null, context.getAuthentication());
Authentication authentication = context.getAuthentication();
assertTrue("Expected anonymous Authentication got " + context,
authentication == null
|| this.trustResolver.isAnonymous(authentication));
}

private UnAuthenticatedMatcher() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.security.test.web.servlet.response;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
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.securityContext;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

/**
* @author Rob Winch
* @since 4.1
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class Gh3409Tests {

@Autowired
private WebApplicationContext context;

private MockMvc mockMvc;

@Before
public void setup() {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}

// gh-3409
@Test
public void unauthenticatedAnonymousUser() throws Exception {
// @formatter:off
this.mockMvc
.perform(get("/public/")
.with(securityContext(new SecurityContextImpl())));

this.mockMvc
.perform(get("/public/"))
.andExpect(unauthenticated());
// @formatter:on
}

@Test
public void unauthenticatedNullAuthenitcation() throws Exception {
// @formatter:off
this.mockMvc
.perform(get("/")
.with(securityContext(new SecurityContextImpl())));

this.mockMvc
.perform(get("/"))
.andExpect(unauthenticated());
// @formatter:on
}

@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
// @formatter:on

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@
*/
package org.springframework.security.test.web.servlet.response;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Expand All @@ -36,6 +33,10 @@
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecurityMockMvcResultMatchersTests.Config.class)
@WebAppConfiguration
Expand All @@ -47,21 +48,32 @@ public class SecurityMockMvcResultMatchersTests {

@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity())
.build();
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}

// SEC-2719
@Test
public void withRolesNotOrderSensitive() throws Exception {
mockMvc.perform(formLogin())
.andExpect(authenticated().withRoles("USER", "SELLER"))
.andExpect(authenticated().withRoles("SELLER", "USER"));
// @formatter:off
this.mockMvc
.perform(formLogin())
.andExpect(authenticated().withRoles("USER", "SELLER"))
.andExpect(authenticated().withRoles("SELLER", "USER"));
// @formatter:on
}

@Test(expected = AssertionError.class)
public void withRolesFailsIfNotAllRoles() throws Exception {
mockMvc.perform(formLogin()).andExpect(authenticated().withRoles("USER"));
// @formatter:off
this.mockMvc
.perform(formLogin())
.andExpect(authenticated().withRoles("USER"));
// @formatter:on
}

@EnableWebSecurity
Expand Down