Skip to content

Commit

Permalink
RequestAttributeSecurityContextRepository never null SecurityContext
Browse files Browse the repository at this point in the history
Previously loadContext(HttpServletRequest) could return a Supplier that
returned a null SecurityContext

This commit ensures that null is never returned by the Supplier by
returning SecurityContextHolder.createEmptyContext() instead.

Closes gh-11606
  • Loading branch information
rwinch committed Aug 8, 2022
1 parent ed58ac7 commit c23324e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,26 @@ public RequestAttributeSecurityContextRepository(String requestAttributeName) {

@Override
public boolean containsContext(HttpServletRequest request) {
return loadContext(request).get() != null;
return getContext(request) != null;
}

@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
SecurityContext context = loadContext(requestResponseHolder.getRequest()).get();
return (context != null) ? context : SecurityContextHolder.createEmptyContext();
return getContextOrEmpty(requestResponseHolder.getRequest());
}

@Override
public Supplier<SecurityContext> loadContext(HttpServletRequest request) {
return () -> (SecurityContext) request.getAttribute(this.requestAttributeName);
return () -> getContextOrEmpty(request);
}

private SecurityContext getContextOrEmpty(HttpServletRequest request) {
SecurityContext context = getContext(request);
return (context != null) ? context : SecurityContextHolder.createEmptyContext();
}

private SecurityContext getContext(HttpServletRequest request) {
return (SecurityContext) request.getAttribute(this.requestAttributeName);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.springframework.security.web.context;

import java.util.function.Supplier;

import org.junit.jupiter.api.Test;

import org.springframework.mock.web.MockHttpServletRequest;
Expand Down Expand Up @@ -67,4 +69,17 @@ void containsContextWhenSavedThenTrue() {
assertThat(this.repository.containsContext(this.request)).isTrue();
}

@Test
void loadDeferredContextWhenNotPresentThenEmptyContext() {
Supplier<SecurityContext> deferredContext = this.repository.loadContext(this.request);
assertThat(deferredContext.get()).isEqualTo(SecurityContextHolder.createEmptyContext());
}

@Test
void loadContextWhenNotPresentThenEmptyContext() {
SecurityContext context = this.repository
.loadContext(new HttpRequestResponseHolder(this.request, this.response));
assertThat(context).isEqualTo(SecurityContextHolder.createEmptyContext());
}

}

0 comments on commit c23324e

Please sign in to comment.