Add AuthorizationManager
Closes gh-8900
This commit is contained in:
committed by
Josh Cummings
parent
5306d4c4d5
commit
34b4b1054f
+69
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright 2002-2020 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authorization.AuthorizationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/**
|
||||
* An authorization filter that restricts access to the URL using
|
||||
* {@link AuthorizationManager}.
|
||||
*
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
public class AuthorizationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final AuthorizationManager<HttpServletRequest> authorizationManager;
|
||||
|
||||
/**
|
||||
* Creates an instance.
|
||||
* @param authorizationManager the {@link AuthorizationManager} to use
|
||||
*/
|
||||
public AuthorizationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) {
|
||||
Assert.notNull(authorizationManager, "authorizationManager cannot be null");
|
||||
this.authorizationManager = authorizationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
this.authorizationManager.verify(this::getAuthentication, request);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private Authentication getAuthentication() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null) {
|
||||
throw new AuthenticationCredentialsNotFoundException(
|
||||
"An Authentication object was not found in the SecurityContext");
|
||||
}
|
||||
return authentication;
|
||||
}
|
||||
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright 2002-2020 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.core.log.LogMessage;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.authorization.AuthorizationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* An {@link AuthorizationManager} which delegates to a specific
|
||||
* {@link AuthorizationManager} based on a {@link RequestMatcher} evaluation.
|
||||
*
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
public final class DelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mappings;
|
||||
|
||||
private DelegatingAuthorizationManager(
|
||||
Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mappings) {
|
||||
Assert.notEmpty(mappings, "mappings cannot be empty");
|
||||
this.mappings = mappings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates to a specific {@link AuthorizationManager} based on a
|
||||
* {@link RequestMatcher} evaluation.
|
||||
* @param authentication the {@link Supplier} of the {@link Authentication} to check
|
||||
* @param request the {@link HttpServletRequest} to check
|
||||
* @return an {@link AuthorizationDecision}. If there is no {@link RequestMatcher}
|
||||
* matching the request, or the {@link AuthorizationManager} could not decide, then
|
||||
* null is returned
|
||||
*/
|
||||
@Override
|
||||
public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) {
|
||||
if (this.logger.isTraceEnabled()) {
|
||||
this.logger.trace(LogMessage.format("Authorizing %s", request));
|
||||
}
|
||||
for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings
|
||||
.entrySet()) {
|
||||
|
||||
RequestMatcher matcher = mapping.getKey();
|
||||
MatchResult matchResult = matcher.matcher(request);
|
||||
if (matchResult.isMatch()) {
|
||||
AuthorizationManager<RequestAuthorizationContext> manager = mapping.getValue();
|
||||
if (this.logger.isTraceEnabled()) {
|
||||
this.logger.trace(LogMessage.format("Checking authorization on %s using %s", request, manager));
|
||||
}
|
||||
return manager.check(authentication,
|
||||
new RequestAuthorizationContext(request, matchResult.getVariables()));
|
||||
}
|
||||
}
|
||||
this.logger.trace("Abstaining since did not find matching RequestMatcher");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a builder for {@link DelegatingAuthorizationManager}.
|
||||
* @return the new {@link Builder} instance
|
||||
*/
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
/**
|
||||
* A builder for {@link DelegatingAuthorizationManager}.
|
||||
*/
|
||||
public static final class Builder {
|
||||
|
||||
private final Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mappings = new LinkedHashMap<>();
|
||||
|
||||
/**
|
||||
* Maps a {@link RequestMatcher} to an {@link AuthorizationManager}.
|
||||
* @param matcher the {@link RequestMatcher} to use
|
||||
* @param manager the {@link AuthorizationManager} to use
|
||||
* @return the {@link Builder} for further customizations
|
||||
*/
|
||||
public Builder add(RequestMatcher matcher, AuthorizationManager<RequestAuthorizationContext> manager) {
|
||||
Assert.notNull(matcher, "matcher cannot be null");
|
||||
Assert.notNull(manager, "manager cannot be null");
|
||||
this.mappings.put(matcher, manager);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link DelegatingAuthorizationManager} instance.
|
||||
* @return the {@link DelegatingAuthorizationManager} instance
|
||||
*/
|
||||
public DelegatingAuthorizationManager build() {
|
||||
return new DelegatingAuthorizationManager(this.mappings);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2002-2020 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* An {@link HttpServletRequest} authorization context.
|
||||
*
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
public final class RequestAuthorizationContext {
|
||||
|
||||
private final HttpServletRequest request;
|
||||
|
||||
private final Map<String, String> variables;
|
||||
|
||||
/**
|
||||
* Creates an instance.
|
||||
* @param request the {@link HttpServletRequest} to use
|
||||
*/
|
||||
public RequestAuthorizationContext(HttpServletRequest request) {
|
||||
this(request, Collections.emptyMap());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance.
|
||||
* @param request the {@link HttpServletRequest} to use
|
||||
* @param variables a map containing key-value pairs representing extracted variable
|
||||
* names and variable values
|
||||
*/
|
||||
public RequestAuthorizationContext(HttpServletRequest request, Map<String, String> variables) {
|
||||
this.request = request;
|
||||
this.variables = variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link HttpServletRequest}.
|
||||
* @return the {@link HttpServletRequest} to use
|
||||
*/
|
||||
public HttpServletRequest getRequest() {
|
||||
return this.request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the extracted variable values where the key is the variable name and the
|
||||
* value is the variable value.
|
||||
* @return a map containing key-value pairs representing extracted variable names and
|
||||
* variable values
|
||||
*/
|
||||
public Map<String, String> getVariables() {
|
||||
return this.variables;
|
||||
}
|
||||
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright 2002-2020 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
|
||||
import org.springframework.security.authorization.AuthorizationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.BDDMockito.willThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* Tests for {@link AuthorizationFilter}.
|
||||
*
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
public class AuthorizationFilterTests {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception {
|
||||
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
|
||||
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
|
||||
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
|
||||
|
||||
SecurityContext securityContext = new SecurityContextImpl();
|
||||
securityContext.setAuthentication(authenticationToken);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
|
||||
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
|
||||
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
|
||||
FilterChain mockFilterChain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(mockRequest, mockResponse, mockFilterChain);
|
||||
|
||||
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
|
||||
verify(mockAuthorizationManager).verify(authenticationCaptor.capture(), eq(mockRequest));
|
||||
Supplier<Authentication> authentication = authenticationCaptor.getValue();
|
||||
assertThat(authentication.get()).isEqualTo(authenticationToken);
|
||||
|
||||
verify(mockFilterChain).doFilter(mockRequest, mockResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain() {
|
||||
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
|
||||
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
|
||||
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
|
||||
|
||||
SecurityContext securityContext = new SecurityContextImpl();
|
||||
securityContext.setAuthentication(authenticationToken);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
|
||||
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
|
||||
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
|
||||
FilterChain mockFilterChain = mock(FilterChain.class);
|
||||
|
||||
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).verify(any(),
|
||||
eq(mockRequest));
|
||||
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
|
||||
.withMessage("Access Denied");
|
||||
|
||||
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
|
||||
verify(mockAuthorizationManager).verify(authenticationCaptor.capture(), eq(mockRequest));
|
||||
Supplier<Authentication> authentication = authenticationCaptor.getValue();
|
||||
assertThat(authentication.get()).isEqualTo(authenticationToken);
|
||||
|
||||
verifyNoInteractions(mockFilterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundException() {
|
||||
AuthorizationFilter filter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated());
|
||||
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
|
||||
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
|
||||
FilterChain mockFilterChain = mock(FilterChain.class);
|
||||
|
||||
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
|
||||
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
|
||||
.withMessage("An Authentication object was not found in the SecurityContext");
|
||||
|
||||
verifyNoInteractions(mockFilterChain);
|
||||
}
|
||||
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2002-2020 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Tests for {@link DelegatingAuthorizationManager}.
|
||||
*
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
public class DelegatingAuthorizationManagerTests {
|
||||
|
||||
@Test
|
||||
public void buildWhenMappingsEmptyThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> DelegatingAuthorizationManager.builder().build())
|
||||
.withMessage("mappings cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addWhenMatcherNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> DelegatingAuthorizationManager.builder()
|
||||
.add(null, (a, o) -> new AuthorizationDecision(true)).build())
|
||||
.withMessage("matcher cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addWhenManagerNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> DelegatingAuthorizationManager.builder().add(new MvcRequestMatcher(null, "/grant"), null).build())
|
||||
.withMessage("manager cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenMultipleMappingsConfiguredThenDelegatesMatchingManager() {
|
||||
DelegatingAuthorizationManager manager = DelegatingAuthorizationManager.builder()
|
||||
.add(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true))
|
||||
.add(new MvcRequestMatcher(null, "/deny"), (a, o) -> new AuthorizationDecision(false))
|
||||
.add(new MvcRequestMatcher(null, "/neutral"), (a, o) -> null).build();
|
||||
|
||||
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
|
||||
AuthorizationDecision grant = manager.check(authentication, new MockHttpServletRequest(null, "/grant"));
|
||||
assertThat(grant).isNotNull();
|
||||
assertThat(grant.isGranted()).isTrue();
|
||||
|
||||
AuthorizationDecision deny = manager.check(authentication, new MockHttpServletRequest(null, "/deny"));
|
||||
assertThat(deny).isNotNull();
|
||||
assertThat(deny.isGranted()).isFalse();
|
||||
|
||||
AuthorizationDecision neutral = manager.check(authentication, new MockHttpServletRequest(null, "/neutral"));
|
||||
assertThat(neutral).isNull();
|
||||
|
||||
AuthorizationDecision abstain = manager.check(authentication, new MockHttpServletRequest(null, "/abstain"));
|
||||
assertThat(abstain).isNull();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user