repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchers.java
/* * Copyright 2002-2023 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.server.util.matcher; import java.util.ArrayList; import java.util.List; import reactor.core.publisher.Mono; import org.springframework.http.HttpMethod; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.pattern.PathPattern; /** * Provides factory methods for creating common {@link ServerWebExchangeMatcher} * * @author Rob Winch * @since 5.0 */ public abstract class ServerWebExchangeMatchers { private ServerWebExchangeMatchers() { } /** * Creates a matcher that matches on the specific method and any of the provided * patterns. * @param method the method to match on. If null, any method will be matched * @param patterns the patterns to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(HttpMethod method, String... patterns) { List<ServerWebExchangeMatcher> matchers = new ArrayList<>(patterns.length); for (String pattern : patterns) { matchers.add(new PathPatternParserServerWebExchangeMatcher(pattern, method)); } return new OrServerWebExchangeMatcher(matchers); } /** * Creates a matcher that matches on any of the provided patterns. * @param patterns the patterns to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(String... patterns) { return pathMatchers(null, patterns); } /** * Creates a matcher that matches on any of the provided {@link PathPattern}s. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(PathPattern... pathPatterns) { return pathMatchers(null, pathPatterns); } /** * Creates a matcher that matches on the specific method and any of the provided * {@link PathPattern}s. * @param method the method to match on. If null, any method will be matched. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(HttpMethod method, PathPattern... pathPatterns) { List<ServerWebExchangeMatcher> matchers = new ArrayList<>(pathPatterns.length); for (PathPattern pathPattern : pathPatterns) { matchers.add(new PathPatternParserServerWebExchangeMatcher(pathPattern, method)); } return new OrServerWebExchangeMatcher(matchers); } /** * Creates a matcher that will match on any of the provided matchers * @param matchers the matchers to match on * @return the matcher to use */ public static ServerWebExchangeMatcher matchers(ServerWebExchangeMatcher... matchers) { return new OrServerWebExchangeMatcher(matchers); } /** * Matches any exchange * @return the matcher to use */ @SuppressWarnings("Convert2Lambda") public static ServerWebExchangeMatcher anyExchange() { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered // LinkedHashMap return new ServerWebExchangeMatcher() { @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return ServerWebExchangeMatcher.MatchResult.match(); } }; } }
3,838
32.094828
102
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcher.java
/* * Copyright 2002-2021 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.server.util.matcher; import reactor.core.publisher.Mono; import org.springframework.security.web.util.matcher.IpAddressMatcher; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Matches a request based on IP Address or subnet mask matching against the remote * address. * * @author Guirong Hu * @since 5.7 */ public final class IpAddressServerWebExchangeMatcher implements ServerWebExchangeMatcher { private final IpAddressMatcher ipAddressMatcher; /** * Takes a specific IP address or a range specified using the IP/Netmask (e.g. * 192.168.1.0/24 or 202.24.0.0/14). * @param ipAddress the address or range of addresses from which the request must * come. */ public IpAddressServerWebExchangeMatcher(String ipAddress) { Assert.hasText(ipAddress, "IP address cannot be empty"); this.ipAddressMatcher = new IpAddressMatcher(ipAddress); } @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { // @formatter:off return Mono.justOrEmpty(exchange.getRequest().getRemoteAddress()) .map((remoteAddress) -> remoteAddress.isUnresolved() ? remoteAddress.getHostString() : remoteAddress.getAddress().getHostAddress()) .map(this.ipAddressMatcher::matches) .flatMap((matches) -> matches ? MatchResult.match() : MatchResult.notMatch()) .switchIfEmpty(MatchResult.notMatch()); // @formatter:on } @Override public String toString() { return "IpAddressServerWebExchangeMatcher{ipAddressMatcher=" + this.ipAddressMatcher + '}'; } }
2,211
33.5625
135
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcher.java
/* * 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.server.util.matcher; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Matches if any of the provided {@link ServerWebExchangeMatcher} match * * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 * @see AndServerWebExchangeMatcher */ public class OrServerWebExchangeMatcher implements ServerWebExchangeMatcher { private static final Log logger = LogFactory.getLog(OrServerWebExchangeMatcher.class); private final List<ServerWebExchangeMatcher> matchers; public OrServerWebExchangeMatcher(List<ServerWebExchangeMatcher> matchers) { Assert.notEmpty(matchers, "matchers cannot be empty"); this.matchers = matchers; } public OrServerWebExchangeMatcher(ServerWebExchangeMatcher... matchers) { this(Arrays.asList(matchers)); } @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Flux.fromIterable(this.matchers) .doOnNext((matcher) -> logger.debug(LogMessage.format("Trying to match using %s", matcher))) .flatMap((matcher) -> matcher.matches(exchange)).filter(MatchResult::isMatch).next() .switchIfEmpty(MatchResult.notMatch()) .doOnNext((matchResult) -> logger.debug(matchResult.isMatch() ? "matched" : "No matches found")); } @Override public String toString() { return "OrServerWebExchangeMatcher{matchers=" + this.matchers + '}'; } }
2,293
32.246377
101
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatcherEntry.java
/* * Copyright 2002-2017 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.server.util.matcher; /** * A rich object for associating a {@link ServerWebExchangeMatcher} to another object. * * @author Rob Winch * @since 5.0 */ public class ServerWebExchangeMatcherEntry<T> { private final ServerWebExchangeMatcher matcher; private final T entry; public ServerWebExchangeMatcherEntry(ServerWebExchangeMatcher matcher, T entry) { this.matcher = matcher; this.entry = entry; } public ServerWebExchangeMatcher getMatcher() { return this.matcher; } public T getEntry() { return this.entry; } }
1,203
25.755556
86
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatcher.java
/* * Copyright 2002-2017 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.server.util.matcher; import java.util.Collections; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * An interface for determining if a {@link ServerWebExchangeMatcher} matches. * * @author Rob Winch * @since 5.0 */ public interface ServerWebExchangeMatcher { /** * Determines if a request matches or not * @param exchange * @return */ Mono<MatchResult> matches(ServerWebExchange exchange); /** * The result of matching */ class MatchResult { private final boolean match; private final Map<String, Object> variables; private MatchResult(boolean match, Map<String, Object> variables) { this.match = match; this.variables = variables; } public boolean isMatch() { return this.match; } /** * Gets potential variables and their values * @return */ public Map<String, Object> getVariables() { return this.variables; } /** * Creates an instance of {@link MatchResult} that is a match with no variables * @return */ public static Mono<MatchResult> match() { return match(Collections.emptyMap()); } /** * * Creates an instance of {@link MatchResult} that is a match with the specified * variables * @param variables * @return */ public static Mono<MatchResult> match(Map<String, Object> variables) { return Mono.just(new MatchResult(true, variables)); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return */ public static Mono<MatchResult> notMatch() { return Mono.just(new MatchResult(false, Collections.emptyMap())); } } }
2,320
22.927835
82
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/PathPatternParserServerWebExchangeMatcher.java
/* * Copyright 2002-2023 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.server.util.matcher; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.http.HttpMethod; import org.springframework.http.server.PathContainer; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.pattern.PathPattern; import org.springframework.web.util.pattern.PathPatternParser; /** * Matches if the {@link PathPattern} matches the path within the application. * * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 */ public final class PathPatternParserServerWebExchangeMatcher implements ServerWebExchangeMatcher { private static final Log logger = LogFactory.getLog(PathPatternParserServerWebExchangeMatcher.class); private final PathPattern pattern; private final HttpMethod method; public PathPatternParserServerWebExchangeMatcher(PathPattern pattern) { this(pattern, null); } public PathPatternParserServerWebExchangeMatcher(PathPattern pattern, HttpMethod method) { Assert.notNull(pattern, "pattern cannot be null"); this.pattern = pattern; this.method = method; } public PathPatternParserServerWebExchangeMatcher(String pattern, HttpMethod method) { Assert.notNull(pattern, "pattern cannot be null"); this.pattern = parse(pattern); this.method = method; } public PathPatternParserServerWebExchangeMatcher(String pattern) { this(pattern, null); } private PathPattern parse(String pattern) { PathPatternParser parser = PathPatternParser.defaultInstance; pattern = parser.initFullPathPattern(pattern); return parser.parse(pattern); } @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); PathContainer path = request.getPath().pathWithinApplication(); if (this.method != null && !this.method.equals(request.getMethod())) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); } }); } boolean match = this.pattern.matches(path); if (!match) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); } }); } Map<String, String> pathVariables = this.pattern.matchAndExtract(path).getUriVariables(); Map<String, Object> variables = new HashMap<>(pathVariables); if (logger.isDebugEnabled()) { logger.debug( "Checking match of request : '" + path + "'; against '" + this.pattern.getPatternString() + "'"); } return MatchResult.match(variables); } @Override public String toString() { return "PathMatcherServerWebExchangeMatcher{" + "pattern='" + this.pattern + '\'' + ", method=" + this.method + '}'; } }
3,838
33.276786
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilter.java
/* * Copyright 2002-2017 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.server.ui; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.security.web.server.csrf.CsrfToken; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.util.HtmlUtils; /** * Generates a default log in page used for authenticating users. * * @author Rob Winch * @since 5.0 */ public class LoginPageGeneratingWebFilter implements WebFilter { private ServerWebExchangeMatcher matcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/login"); private Map<String, String> oauth2AuthenticationUrlToClientName = new HashMap<>(); private boolean formLoginEnabled; public void setFormLoginEnabled(boolean enabled) { this.formLoginEnabled = enabled; } public void setOauth2AuthenticationUrlToClientName(Map<String, String> oauth2AuthenticationUrlToClientName) { Assert.notNull(oauth2AuthenticationUrlToClientName, "oauth2AuthenticationUrlToClientName cannot be null"); this.oauth2AuthenticationUrlToClientName = oauth2AuthenticationUrlToClientName; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.matcher.matches(exchange).filter(ServerWebExchangeMatcher.MatchResult::isMatch) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())).flatMap((matchResult) -> render(exchange)); } private Mono<Void> render(ServerWebExchange exchange) { ServerHttpResponse result = exchange.getResponse(); result.setStatusCode(HttpStatus.OK); result.getHeaders().setContentType(MediaType.TEXT_HTML); return result.writeWith(createBuffer(exchange)); } private Mono<DataBuffer> createBuffer(ServerWebExchange exchange) { Mono<CsrfToken> token = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); return token.map(LoginPageGeneratingWebFilter::csrfToken).defaultIfEmpty("").map((csrfTokenHtmlInput) -> { byte[] bytes = createPage(exchange, csrfTokenHtmlInput); DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); return bufferFactory.wrap(bytes); }); } private byte[] createPage(ServerWebExchange exchange, String csrfTokenHtmlInput) { MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); String contextPath = exchange.getRequest().getPath().contextPath().value(); StringBuilder page = new StringBuilder(); page.append("<!DOCTYPE html>\n"); page.append("<html lang=\"en\">\n"); page.append(" <head>\n"); page.append(" <meta charset=\"utf-8\">\n"); page.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"); page.append(" <meta name=\"description\" content=\"\">\n"); page.append(" <meta name=\"author\" content=\"\">\n"); page.append(" <title>Please sign in</title>\n"); page.append(" <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" " + "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" " + "crossorigin=\"anonymous\">\n"); page.append(" <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" " + "rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"); page.append(" </head>\n"); page.append(" <body>\n"); page.append(" <div class=\"container\">\n"); page.append(formLogin(queryParams, contextPath, csrfTokenHtmlInput)); page.append(oauth2LoginLinks(queryParams, contextPath, this.oauth2AuthenticationUrlToClientName)); page.append(" </div>\n"); page.append(" </body>\n"); page.append("</html>"); return page.toString().getBytes(Charset.defaultCharset()); } private String formLogin(MultiValueMap<String, String> queryParams, String contextPath, String csrfTokenHtmlInput) { if (!this.formLoginEnabled) { return ""; } boolean isError = queryParams.containsKey("error"); boolean isLogoutSuccess = queryParams.containsKey("logout"); StringBuilder page = new StringBuilder(); page.append(" <form class=\"form-signin\" method=\"post\" action=\"" + contextPath + "/login\">\n"); page.append(" <h2 class=\"form-signin-heading\">Please sign in</h2>\n"); page.append(createError(isError)); page.append(createLogoutSuccess(isLogoutSuccess)); page.append(" <p>\n"); page.append(" <label for=\"username\" class=\"sr-only\">Username</label>\n"); page.append(" <input type=\"text\" id=\"username\" name=\"username\" " + "class=\"form-control\" placeholder=\"Username\" required autofocus>\n"); page.append(" </p>\n" + " <p>\n"); page.append(" <label for=\"password\" class=\"sr-only\">Password</label>\n"); page.append(" <input type=\"password\" id=\"password\" name=\"password\" " + "class=\"form-control\" placeholder=\"Password\" required>\n"); page.append(" </p>\n"); page.append(csrfTokenHtmlInput); page.append(" <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n"); page.append(" </form>\n"); return page.toString(); } private static String oauth2LoginLinks(MultiValueMap<String, String> queryParams, String contextPath, Map<String, String> oauth2AuthenticationUrlToClientName) { if (oauth2AuthenticationUrlToClientName.isEmpty()) { return ""; } boolean isError = queryParams.containsKey("error"); StringBuilder sb = new StringBuilder(); sb.append("<div class=\"container\"><h2 class=\"form-signin-heading\">Login with OAuth 2.0</h2>"); sb.append(createError(isError)); sb.append("<table class=\"table table-striped\">\n"); for (Map.Entry<String, String> clientAuthenticationUrlToClientName : oauth2AuthenticationUrlToClientName .entrySet()) { sb.append(" <tr><td>"); String url = clientAuthenticationUrlToClientName.getKey(); sb.append("<a href=\"").append(contextPath).append(url).append("\">"); String clientName = HtmlUtils.htmlEscape(clientAuthenticationUrlToClientName.getValue()); sb.append(clientName); sb.append("</a>"); sb.append("</td></tr>\n"); } sb.append("</table></div>\n"); return sb.toString(); } private static String csrfToken(CsrfToken token) { return " <input type=\"hidden\" name=\"" + token.getParameterName() + "\" value=\"" + token.getToken() + "\">\n"; } private static String createError(boolean isError) { return isError ? "<div class=\"alert alert-danger\" role=\"alert\">Invalid credentials</div>" : ""; } private static String createLogoutSuccess(boolean isLogoutSuccess) { return isLogoutSuccess ? "<div class=\"alert alert-success\" role=\"alert\">You have been signed out</div>" : ""; } }
8,083
44.162011
117
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java
/* * Copyright 2002-2022 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.server.ui; import java.nio.charset.Charset; import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.security.web.server.csrf.CsrfToken; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Generates a default log out page. * * @author Rob Winch * @since 5.0 */ public class LogoutPageGeneratingWebFilter implements WebFilter { private ServerWebExchangeMatcher matcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/logout"); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.matcher.matches(exchange).filter(ServerWebExchangeMatcher.MatchResult::isMatch) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())).flatMap((matchResult) -> render(exchange)); } private Mono<Void> render(ServerWebExchange exchange) { ServerHttpResponse result = exchange.getResponse(); result.setStatusCode(HttpStatus.OK); result.getHeaders().setContentType(MediaType.TEXT_HTML); return result.writeWith(createBuffer(exchange)); } private Mono<DataBuffer> createBuffer(ServerWebExchange exchange) { Mono<CsrfToken> token = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); String contextPath = exchange.getRequest().getPath().contextPath().value(); return token.map(LogoutPageGeneratingWebFilter::csrfToken).defaultIfEmpty("").map((csrfTokenHtmlInput) -> { byte[] bytes = createPage(csrfTokenHtmlInput, contextPath); DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); return bufferFactory.wrap(bytes); }); } private static byte[] createPage(String csrfTokenHtmlInput, String contextPath) { StringBuilder page = new StringBuilder(); page.append("<!DOCTYPE html>\n"); page.append("<html lang=\"en\">\n"); page.append(" <head>\n"); page.append(" <meta charset=\"utf-8\">\n"); page.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"); page.append(" <meta name=\"description\" content=\"\">\n"); page.append(" <meta name=\"author\" content=\"\">\n"); page.append(" <title>Confirm Log Out?</title>\n"); page.append(" <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" " + "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"); page.append(" <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" " + "rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"); page.append(" </head>\n"); page.append(" <body>\n"); page.append(" <div class=\"container\">\n"); page.append(" <form class=\"form-signin\" method=\"post\" action=\"" + contextPath + "/logout\">\n"); page.append(" <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"); page.append(csrfTokenHtmlInput); page.append(" <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n"); page.append(" </form>\n"); page.append(" </div>\n"); page.append(" </body>\n"); page.append("</html>"); return page.toString().getBytes(Charset.defaultCharset()); } private static String csrfToken(CsrfToken token) { return " <input type=\"hidden\" name=\"" + token.getParameterName() + "\" value=\"" + token.getToken() + "\">\n"; } }
4,647
44.126214
143
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/CsrfWebFilter.java
/* * Copyright 2002-2022 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.server.csrf; import java.security.MessageDigest; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import reactor.core.publisher.Mono; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler; import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * <p> * Applies * <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" >CSRF</a> * protection using a synchronizer token pattern. Developers are required to ensure that * {@link CsrfWebFilter} is invoked for any request that allows state to change. Typically * this just means that they should ensure their web application follows proper REST * semantics (i.e. do not change state with the HTTP methods GET, HEAD, TRACE, OPTIONS). * </p> * * <p> * Typically the {@link ServerCsrfTokenRepository} implementation chooses to store the * {@link CsrfToken} in {@link org.springframework.web.server.WebSession} with * {@link WebSessionServerCsrfTokenRepository}. This is preferred to storing the token in * a cookie which can be modified by a client application. * </p> * <p> * The {@code Mono&lt;CsrfToken&gt;} is exposes as a request attribute with the name of * {@code CsrfToken.class.getName()}. If the token is new it will automatically be saved * at the time it is subscribed. * </p> * * @author Rob Winch * @author Parikshit Dutta * @author Steve Riesenberg * @since 5.0 */ public class CsrfWebFilter implements WebFilter { public static final ServerWebExchangeMatcher DEFAULT_CSRF_MATCHER = new DefaultRequireCsrfProtectionMatcher(); /** * The attribute name to use when marking a given request as one that should not be * filtered. * * To use, set the attribute on your {@link ServerWebExchange}: <pre> * CsrfWebFilter.skipExchange(exchange); * </pre> */ private static final String SHOULD_NOT_FILTER = "SHOULD_NOT_FILTER" + CsrfWebFilter.class.getName(); private ServerWebExchangeMatcher requireCsrfProtectionMatcher = DEFAULT_CSRF_MATCHER; private ServerCsrfTokenRepository csrfTokenRepository = new WebSessionServerCsrfTokenRepository(); private ServerAccessDeniedHandler accessDeniedHandler = new HttpStatusServerAccessDeniedHandler( HttpStatus.FORBIDDEN); private ServerCsrfTokenRequestHandler requestHandler = new XorServerCsrfTokenRequestAttributeHandler(); public void setAccessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "accessDeniedHandler"); this.accessDeniedHandler = accessDeniedHandler; } public void setCsrfTokenRepository(ServerCsrfTokenRepository csrfTokenRepository) { Assert.notNull(csrfTokenRepository, "csrfTokenRepository cannot be null"); this.csrfTokenRepository = csrfTokenRepository; } public void setRequireCsrfProtectionMatcher(ServerWebExchangeMatcher requireCsrfProtectionMatcher) { Assert.notNull(requireCsrfProtectionMatcher, "requireCsrfProtectionMatcher cannot be null"); this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher; } /** * Specifies a {@link ServerCsrfTokenRequestHandler} that is used to make the * {@code CsrfToken} available as an exchange attribute. * <p> * The default is {@link XorServerCsrfTokenRequestAttributeHandler}. * @param requestHandler the {@link ServerCsrfTokenRequestHandler} to use * @since 5.8 */ public void setRequestHandler(ServerCsrfTokenRequestHandler requestHandler) { Assert.notNull(requestHandler, "requestHandler cannot be null"); this.requestHandler = requestHandler; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { if (Boolean.TRUE.equals(exchange.getAttribute(SHOULD_NOT_FILTER))) { return chain.filter(exchange).then(Mono.empty()); } return this.requireCsrfProtectionMatcher.matches(exchange).filter(MatchResult::isMatch) .filter((matchResult) -> !exchange.getAttributes().containsKey(CsrfToken.class.getName())) .flatMap((m) -> validateToken(exchange)).flatMap((m) -> continueFilterChain(exchange, chain)) .switchIfEmpty(continueFilterChain(exchange, chain).then(Mono.empty())) .onErrorResume(CsrfException.class, (ex) -> this.accessDeniedHandler.handle(exchange, ex)); } public static void skipExchange(ServerWebExchange exchange) { exchange.getAttributes().put(SHOULD_NOT_FILTER, Boolean.TRUE); } private Mono<Void> validateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange) .switchIfEmpty( Mono.defer(() -> Mono.error(new CsrfException("An expected CSRF token cannot be found")))) .filterWhen((expected) -> containsValidCsrfToken(exchange, expected)) .switchIfEmpty(Mono.defer(() -> Mono.error(new CsrfException("Invalid CSRF Token")))).then(); } private Mono<Boolean> containsValidCsrfToken(ServerWebExchange exchange, CsrfToken expected) { return this.requestHandler.resolveCsrfTokenValue(exchange, expected) .map((actual) -> equalsConstantTime(actual, expected.getToken())); } private Mono<Void> continueFilterChain(ServerWebExchange exchange, WebFilterChain chain) { return Mono.defer(() -> { Mono<CsrfToken> csrfToken = csrfToken(exchange); this.requestHandler.handle(exchange, csrfToken); return chain.filter(exchange); }); } private Mono<CsrfToken> csrfToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange).switchIfEmpty(generateToken(exchange)); } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.generateToken(exchange) .delayUntil((token) -> this.csrfTokenRepository.saveToken(exchange, token)).cache(); } private static class DefaultRequireCsrfProtectionMatcher implements ServerWebExchangeMatcher { private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS)); @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()).flatMap((r) -> Mono.justOrEmpty(r.getMethod())) .filter(ALLOWED_METHODS::contains).flatMap((m) -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); } } }
7,979
39.714286
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/ServerCsrfTokenRequestAttributeHandler.java
/* * Copyright 2002-2022 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.server.csrf; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.codec.multipart.FormFieldPart; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * An implementation of the {@link ServerCsrfTokenRequestHandler} interface that is * capable of making the {@link CsrfToken} available as an exchange attribute and * resolving the token value as either a form data value or header of the request. * * @author Steve Riesenberg * @since 5.8 */ public class ServerCsrfTokenRequestAttributeHandler implements ServerCsrfTokenRequestHandler { private boolean isTokenFromMultipartDataEnabled; @Override public void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken) { Assert.notNull(exchange, "exchange cannot be null"); Assert.notNull(csrfToken, "csrfToken cannot be null"); exchange.getAttributes().put(CsrfToken.class.getName(), csrfToken); } @Override public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { return ServerCsrfTokenRequestHandler.super.resolveCsrfTokenValue(exchange, csrfToken) .switchIfEmpty(tokenFromMultipartData(exchange, csrfToken)); } /** * Specifies if the {@code ServerCsrfTokenRequestResolver} should try to resolve the * actual CSRF token from the body of multipart data requests. * @param tokenFromMultipartDataEnabled true if should read from multipart form body, * else false. Default is false */ public void setTokenFromMultipartDataEnabled(boolean tokenFromMultipartDataEnabled) { this.isTokenFromMultipartDataEnabled = tokenFromMultipartDataEnabled; } private Mono<String> tokenFromMultipartData(ServerWebExchange exchange, CsrfToken expected) { if (!this.isTokenFromMultipartDataEnabled) { return Mono.empty(); } ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); MediaType contentType = headers.getContentType(); if (!MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) { return Mono.empty(); } return exchange.getMultipartData().map((d) -> d.getFirst(expected.getParameterName())).cast(FormFieldPart.class) .map(FormFieldPart::value); } }
3,031
37.871795
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/DefaultCsrfToken.java
/* * Copyright 2002-2017 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.server.csrf; import org.springframework.util.Assert; /** * A CSRF token that is used to protect against CSRF attacks. * * @author Rob Winch * @since 5.0 */ @SuppressWarnings("serial") public final class DefaultCsrfToken implements CsrfToken { private final String token; private final String parameterName; private final String headerName; /** * Creates a new instance * @param headerName the HTTP header name to use * @param parameterName the HTTP parameter name to use * @param token the value of the token (i.e. expected value of the HTTP parameter of * parametername). */ public DefaultCsrfToken(String headerName, String parameterName, String token) { Assert.hasLength(headerName, "headerName cannot be null or empty"); Assert.hasLength(parameterName, "parameterName cannot be null or empty"); Assert.hasLength(token, "token cannot be null or empty"); this.headerName = headerName; this.parameterName = parameterName; this.token = token; } @Override public String getHeaderName() { return this.headerName; } @Override public String getParameterName() { return this.parameterName; } @Override public String getToken() { return this.token; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof CsrfToken)) { return false; } CsrfToken other = (CsrfToken) obj; if (!getToken().equals(other.getToken())) { return false; } if (!getParameterName().equals(other.getParameterName())) { return false; } return getHeaderName().equals(other.getHeaderName()); } @Override public int hashCode() { int result = getToken().hashCode(); result = 31 * result + getParameterName().hashCode(); result = 31 * result + getHeaderName().hashCode(); return result; } }
2,484
25.43617
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/XorServerCsrfTokenRequestAttributeHandler.java
/* * Copyright 2002-2022 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.server.csrf; import java.security.SecureRandom; import java.util.Base64; import reactor.core.publisher.Mono; import org.springframework.security.crypto.codec.Utf8; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * An implementation of the {@link ServerCsrfTokenRequestAttributeHandler} and * {@link ServerCsrfTokenRequestResolver} interfaces that is capable of masking the value * of the {@link CsrfToken} on each request and resolving the raw token value from the * masked value as either a form data value or header of the request. * * @author Steve Riesenberg * @since 5.8 */ public final class XorServerCsrfTokenRequestAttributeHandler extends ServerCsrfTokenRequestAttributeHandler { private SecureRandom secureRandom = new SecureRandom(); /** * Specifies the {@code SecureRandom} used to generate random bytes that are used to * mask the value of the {@link CsrfToken} on each request. * @param secureRandom the {@code SecureRandom} to use to generate random bytes */ public void setSecureRandom(SecureRandom secureRandom) { Assert.notNull(secureRandom, "secureRandom cannot be null"); this.secureRandom = secureRandom; } @Override public void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken) { Assert.notNull(exchange, "exchange cannot be null"); Assert.notNull(csrfToken, "csrfToken cannot be null"); Mono<CsrfToken> updatedCsrfToken = csrfToken.map((token) -> new DefaultCsrfToken(token.getHeaderName(), token.getParameterName(), createXoredCsrfToken(this.secureRandom, token.getToken()))) .cast(CsrfToken.class).cache(); super.handle(exchange, updatedCsrfToken); } @Override public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { return super.resolveCsrfTokenValue(exchange, csrfToken) .flatMap((actualToken) -> Mono.justOrEmpty(getTokenValue(actualToken, csrfToken.getToken()))); } private static String getTokenValue(String actualToken, String token) { byte[] actualBytes; try { actualBytes = Base64.getUrlDecoder().decode(actualToken); } catch (Exception ex) { return null; } byte[] tokenBytes = Utf8.encode(token); int tokenSize = tokenBytes.length; if (actualBytes.length < tokenSize) { return null; } // extract token and random bytes int randomBytesSize = actualBytes.length - tokenSize; byte[] xoredCsrf = new byte[tokenSize]; byte[] randomBytes = new byte[randomBytesSize]; System.arraycopy(actualBytes, 0, randomBytes, 0, randomBytesSize); System.arraycopy(actualBytes, randomBytesSize, xoredCsrf, 0, tokenSize); byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf); return Utf8.decode(csrfBytes); } private static String createXoredCsrfToken(SecureRandom secureRandom, String token) { byte[] tokenBytes = Utf8.encode(token); byte[] randomBytes = new byte[tokenBytes.length]; secureRandom.nextBytes(randomBytes); byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes); byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length]; System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length); System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length); return Base64.getUrlEncoder().encodeToString(combinedBytes); } private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) { int len = Math.min(randomBytes.length, csrfBytes.length); byte[] xoredCsrf = new byte[len]; System.arraycopy(csrfBytes, 0, xoredCsrf, 0, csrfBytes.length); for (int i = 0; i < len; i++) { xoredCsrf[i] ^= randomBytes[i]; } return xoredCsrf; } }
4,312
35.550847
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/CsrfException.java
/* * Copyright 2002-2017 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.server.csrf; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.csrf.CsrfToken; /** * Thrown when an invalid or missing {@link CsrfToken} is found in the HttpServletRequest * * @author Rob Winch * @since 3.2 */ @SuppressWarnings("serial") public class CsrfException extends AccessDeniedException { public CsrfException(String message) { super(message); } }
1,089
29.277778
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/ServerCsrfTokenRequestHandler.java
/* * Copyright 2002-2022 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.server.csrf; import reactor.core.publisher.Mono; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * A callback interface that is used to make the {@link CsrfToken} created by the * {@link ServerCsrfTokenRepository} available as an exchange attribute. Implementations * of this interface may choose to perform additional tasks or customize how the token is * made available to the application through exchange attributes. * * @author Steve Riesenberg * @since 5.8 * @see ServerCsrfTokenRequestAttributeHandler */ @FunctionalInterface public interface ServerCsrfTokenRequestHandler extends ServerCsrfTokenRequestResolver { /** * Handles a request using a {@link CsrfToken}. * @param exchange the {@code ServerWebExchange} with the request being handled * @param csrfToken the {@code Mono<CsrfToken>} created by the * {@link ServerCsrfTokenRepository} */ void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken); @Override default Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { Assert.notNull(exchange, "exchange cannot be null"); Assert.notNull(csrfToken, "csrfToken cannot be null"); return exchange.getFormData().flatMap((data) -> Mono.justOrEmpty(data.getFirst(csrfToken.getParameterName()))) .switchIfEmpty( Mono.justOrEmpty(exchange.getRequest().getHeaders().getFirst(csrfToken.getHeaderName()))); } }
2,116
37.490909
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/ServerCsrfTokenRequestResolver.java
/* * Copyright 2002-2022 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.server.csrf; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * Implementations of this interface are capable of resolving the token value of a * {@link CsrfToken} from the provided {@code ServerWebExchange}. Used by the * {@link CsrfWebFilter}. * * @author Steve Riesenberg * @since 5.8 * @see ServerCsrfTokenRequestAttributeHandler */ @FunctionalInterface public interface ServerCsrfTokenRequestResolver { /** * Returns the token value resolved from the provided {@code ServerWebExchange} and * {@link CsrfToken} or {@code Mono.empty()} if not available. * @param exchange the {@code ServerWebExchange} with the request being processed * @param csrfToken the {@link CsrfToken} created by the * {@link ServerCsrfTokenRepository} * @return the token value resolved from the request */ Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken); }
1,613
34.086957
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandler.java
/* * Copyright 2002-2018 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.server.csrf; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.authentication.logout.ServerLogoutHandler; import org.springframework.util.Assert; /** * {@link CsrfServerLogoutHandler} is in charge of removing the {@link CsrfToken} upon * logout. A new {@link CsrfToken} will then be generated by the framework upon the next * request. * * @author Eric Deandrea * @since 5.1 */ public class CsrfServerLogoutHandler implements ServerLogoutHandler { private final ServerCsrfTokenRepository csrfTokenRepository; /** * Creates a new instance * @param csrfTokenRepository The {@link ServerCsrfTokenRepository} to use */ public CsrfServerLogoutHandler(ServerCsrfTokenRepository csrfTokenRepository) { Assert.notNull(csrfTokenRepository, "csrfTokenRepository cannot be null"); this.csrfTokenRepository = csrfTokenRepository; } /** * Clears the {@link CsrfToken} * @param exchange the exchange * @param authentication the {@link Authentication} * @return A completion notification (success or error) */ @Override public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) { return this.csrfTokenRepository.saveToken(exchange.getExchange(), null); } }
2,031
33.440678
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/CookieServerCsrfTokenRepository.java
/* * Copyright 2002-2022 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.server.csrf; import java.util.UUID; import java.util.function.Consumer; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import org.springframework.http.HttpCookie; import org.springframework.http.ResponseCookie; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; /** * A {@link ServerCsrfTokenRepository} that persists the CSRF token in a cookie named * "XSRF-TOKEN" and reads from the header "X-XSRF-TOKEN" following the conventions of * AngularJS. When using with AngularJS be sure to use {@link #withHttpOnlyFalse()} . * * @author Eric Deandrea * @author Thomas Vitale * @author Alonso Araya * @author Alex Montoya * @since 5.1 */ public final class CookieServerCsrfTokenRepository implements ServerCsrfTokenRepository { static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN"; static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf"; static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN"; private String parameterName = DEFAULT_CSRF_PARAMETER_NAME; private String headerName = DEFAULT_CSRF_HEADER_NAME; private String cookiePath; private String cookieDomain; private String cookieName = DEFAULT_CSRF_COOKIE_NAME; private boolean cookieHttpOnly = true; private Boolean secure; private int cookieMaxAge = -1; private Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer = (builder) -> { }; /** * Add a {@link Consumer} for a {@code ResponseCookieBuilder} that will be invoked for * each cookie being built, just before the call to {@code build()}. * @param cookieCustomizer consumer for a cookie builder * @since 6.1 */ public void setCookieCustomizer(Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer) { Assert.notNull(cookieCustomizer, "cookieCustomizer must not be null"); this.cookieCustomizer = cookieCustomizer; } /** * Factory method to conveniently create an instance that has creates cookies with * {@link ResponseCookie#isHttpOnly} set to false. * @return an instance of CookieCsrfTokenRepository that creates cookies with * {@link ResponseCookie#isHttpOnly} set to false */ public static CookieServerCsrfTokenRepository withHttpOnlyFalse() { CookieServerCsrfTokenRepository result = new CookieServerCsrfTokenRepository(); result.setCookieCustomizer((cookie) -> cookie.httpOnly(false)); return result; } @Override public Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return Mono.fromCallable(this::createCsrfToken).subscribeOn(Schedulers.boundedElastic()); } @Override public Mono<Void> saveToken(ServerWebExchange exchange, CsrfToken token) { return Mono.fromRunnable(() -> { String tokenValue = (token != null) ? token.getToken() : ""; // @formatter:off ResponseCookie.ResponseCookieBuilder cookieBuilder = ResponseCookie .from(this.cookieName, tokenValue) .domain(this.cookieDomain) .httpOnly(this.cookieHttpOnly) .maxAge(!tokenValue.isEmpty() ? this.cookieMaxAge : 0) .path((this.cookiePath != null) ? this.cookiePath : getRequestContext(exchange.getRequest())) .secure((this.secure != null) ? this.secure : (exchange.getRequest().getSslInfo() != null)); this.cookieCustomizer.accept(cookieBuilder); // @formatter:on exchange.getResponse().addCookie(cookieBuilder.build()); }); } @Override public Mono<CsrfToken> loadToken(ServerWebExchange exchange) { return Mono.fromCallable(() -> { HttpCookie csrfCookie = exchange.getRequest().getCookies().getFirst(this.cookieName); if ((csrfCookie == null) || !StringUtils.hasText(csrfCookie.getValue())) { return null; } return createCsrfToken(csrfCookie.getValue()); }); } /** * @deprecated Use {@link #setCookieCustomizer(Consumer)} instead. */ @Deprecated(since = "6.1") public void setCookieHttpOnly(boolean cookieHttpOnly) { this.cookieHttpOnly = cookieHttpOnly; } /** * Sets the cookie name * @param cookieName The cookie name */ public void setCookieName(String cookieName) { Assert.hasLength(cookieName, "cookieName can't be null"); this.cookieName = cookieName; } /** * Sets the parameter name * @param parameterName The parameter name */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName can't be null"); this.parameterName = parameterName; } /** * Sets the header name * @param headerName The header name */ public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName can't be null"); this.headerName = headerName; } /** * Sets the cookie path * @param cookiePath The cookie path */ public void setCookiePath(String cookiePath) { this.cookiePath = cookiePath; } /** * @deprecated Use {@link #setCookieCustomizer(Consumer)} instead. */ @Deprecated(since = "6.1") public void setCookieDomain(String cookieDomain) { this.cookieDomain = cookieDomain; } /** * @since 5.5 * @deprecated Use {@link #setCookieCustomizer(Consumer)} instead. */ @Deprecated(since = "6.1") public void setSecure(boolean secure) { this.secure = secure; } /** * @since 5.8 * @deprecated Use {@link #setCookieCustomizer(Consumer)} instead. */ @Deprecated(since = "6.1") public void setCookieMaxAge(int cookieMaxAge) { Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge cannot be zero"); this.cookieMaxAge = cookieMaxAge; } private CsrfToken createCsrfToken() { return createCsrfToken(createNewToken()); } private CsrfToken createCsrfToken(String tokenValue) { return new DefaultCsrfToken(this.headerName, this.parameterName, tokenValue); } private String createNewToken() { return UUID.randomUUID().toString(); } private String getRequestContext(ServerHttpRequest request) { String contextPath = request.getPath().contextPath().value(); return StringUtils.hasLength(contextPath) ? contextPath : "/"; } }
6,710
30.213953
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepository.java
/* * Copyright 2002-2017 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.server.csrf; import java.util.Map; import java.util.UUID; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * A {@link ServerCsrfTokenRepository} that stores the {@link CsrfToken} in the * {@link HttpSession}. * * @author Rob Winch * @since 5.0 */ public class WebSessionServerCsrfTokenRepository implements ServerCsrfTokenRepository { private static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf"; private static final String DEFAULT_CSRF_HEADER_NAME = "X-CSRF-TOKEN"; private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = WebSessionServerCsrfTokenRepository.class.getName() .concat(".CSRF_TOKEN"); private String parameterName = DEFAULT_CSRF_PARAMETER_NAME; private String headerName = DEFAULT_CSRF_HEADER_NAME; private String sessionAttributeName = DEFAULT_CSRF_TOKEN_ATTR_NAME; @Override public Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return Mono.fromCallable(() -> createCsrfToken()).subscribeOn(Schedulers.boundedElastic()); } @Override public Mono<Void> saveToken(ServerWebExchange exchange, CsrfToken token) { return exchange.getSession().doOnNext((session) -> putToken(session.getAttributes(), token)) .flatMap((session) -> session.changeSessionId()); } private void putToken(Map<String, Object> attributes, CsrfToken token) { if (token == null) { attributes.remove(this.sessionAttributeName); } else { attributes.put(this.sessionAttributeName, token); } } @Override public Mono<CsrfToken> loadToken(ServerWebExchange exchange) { return exchange.getSession().filter((session) -> session.getAttributes().containsKey(this.sessionAttributeName)) .map((session) -> session.getAttribute(this.sessionAttributeName)); } /** * Sets the {@link HttpServletRequest} parameter name that the {@link CsrfToken} is * expected to appear on * @param parameterName the new parameter name to use */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName cannot be null or empty"); this.parameterName = parameterName; } /** * Sets the header name that the {@link CsrfToken} is expected to appear on and the * header that the response will contain the {@link CsrfToken}. * @param headerName the new header name to use */ public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName cannot be null or empty"); this.headerName = headerName; } /** * Sets the {@link HttpSession} attribute name that the {@link CsrfToken} is stored in * @param sessionAttributeName the new attribute name to use */ public void setSessionAttributeName(String sessionAttributeName) { Assert.hasLength(sessionAttributeName, "sessionAttributename cannot be null or empty"); this.sessionAttributeName = sessionAttributeName; } private CsrfToken createCsrfToken() { return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken()); } private String createNewToken() { return UUID.randomUUID().toString(); } }
3,896
32.594828
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/CsrfToken.java
/* * Copyright 2002-2017 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.server.csrf; import java.io.Serializable; /** * @author Rob Winch * @since 5.0 */ public interface CsrfToken extends Serializable { /** * Gets the HTTP header that the CSRF is populated on the response and can be placed * on requests instead of the parameter. Cannot be null. * @return the HTTP header that the CSRF is populated on the response and can be * placed on requests instead of the parameter */ String getHeaderName(); /** * Gets the HTTP parameter name that should contain the token. Cannot be null. * @return the HTTP parameter name that should contain the token. */ String getParameterName(); /** * Gets the token value. Cannot be null. * @return the token value */ String getToken(); }
1,401
28.208333
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/csrf/ServerCsrfTokenRepository.java
/* * Copyright 2002-2017 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.server.csrf; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * An API to allow changing the method in which the expected {@link CsrfToken} is * associated to the {@link ServerWebExchange}. For example, it may be stored in * {@link org.springframework.web.server.WebSession}. * * @author Rob Winch * @since 5.0 * @see WebSessionServerCsrfTokenRepository * */ public interface ServerCsrfTokenRepository { /** * Generates a {@link CsrfToken} * @param exchange the {@link ServerWebExchange} to use * @return the {@link CsrfToken} that was generated. Cannot be null. */ Mono<CsrfToken> generateToken(ServerWebExchange exchange); /** * Saves the {@link CsrfToken} using the {@link ServerWebExchange}. If the * {@link CsrfToken} is null, it is the same as deleting it. * @param exchange the {@link ServerWebExchange} to use * @param token the {@link CsrfToken} to save or null to delete */ Mono<Void> saveToken(ServerWebExchange exchange, CsrfToken token); /** * Loads the expected {@link CsrfToken} from the {@link ServerWebExchange} * @param exchange the {@link ServerWebExchange} to use * @return the {@link CsrfToken} or null if none exists */ Mono<CsrfToken> loadToken(ServerWebExchange exchange); }
1,959
32.793103
81
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilter.java
/* * Copyright 2002-2017 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.server.context; import reactor.core.publisher.Mono; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Override the {@link ServerWebExchange#getPrincipal()} to be looked up using * {@link ReactiveSecurityContextHolder}. * * @author Rob Winch * @since 5.0 */ public class SecurityContextServerWebExchangeWebFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(new SecurityContextServerWebExchange(exchange, ReactiveSecurityContextHolder.getContext())); } }
1,416
32.738095
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/ServerSecurityContextRepository.java
/* * Copyright 2002-2017 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.server.context; import reactor.core.publisher.Mono; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.server.ServerWebExchange; /** * Strategy used for persisting a {@link SecurityContext} between requests. * * @author Rob Winch * @since 5.0 * @see ReactorContextWebFilter */ public interface ServerSecurityContextRepository { /** * Saves the SecurityContext * @param exchange the exchange to associate to the SecurityContext * @param context the SecurityContext to save * @return a completion notification (success or error) */ Mono<Void> save(ServerWebExchange exchange, SecurityContext context); /** * Loads the SecurityContext associated with the {@link ServerWebExchange} * @param exchange the exchange to look up the {@link SecurityContext} * @return the {@link SecurityContext} to lookup or empty if not found. Never null */ Mono<SecurityContext> load(ServerWebExchange exchange); }
1,635
32.387755
83
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/WebSessionServerSecurityContextRepository.java
/* * 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.server.context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.security.core.context.SecurityContext; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; /** * Stores the {@link SecurityContext} in the * {@link org.springframework.web.server.WebSession}. When a {@link SecurityContext} is * saved, the session id is changed to prevent session fixation attacks. * * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 */ public class WebSessionServerSecurityContextRepository implements ServerSecurityContextRepository { private static final Log logger = LogFactory.getLog(WebSessionServerSecurityContextRepository.class); /** * The default session attribute name to save and load the {@link SecurityContext} */ public static final String DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME = "SPRING_SECURITY_CONTEXT"; private String springSecurityContextAttrName = DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME; private boolean cacheSecurityContext; /** * Sets the session attribute name used to save and load the {@link SecurityContext} * @param springSecurityContextAttrName the session attribute name to use to save and * load the {@link SecurityContext} */ public void setSpringSecurityContextAttrName(String springSecurityContextAttrName) { Assert.hasText(springSecurityContextAttrName, "springSecurityContextAttrName cannot be null or empty"); this.springSecurityContextAttrName = springSecurityContextAttrName; } /** * If set to true the result of {@link #load(ServerWebExchange)} will use * {@link Mono#cache()} to prevent multiple lookups. * @param cacheSecurityContext true if {@link Mono#cache()} should be used, else * false. */ public void setCacheSecurityContext(boolean cacheSecurityContext) { this.cacheSecurityContext = cacheSecurityContext; } @Override public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) { return exchange.getSession().doOnNext((session) -> { if (context == null) { session.getAttributes().remove(this.springSecurityContextAttrName); logger.debug(LogMessage.format("Removed SecurityContext stored in WebSession: '%s'", session)); } else { session.getAttributes().put(this.springSecurityContextAttrName, context); logger.debug(LogMessage.format("Saved SecurityContext '%s' in WebSession: '%s'", context, session)); } }).flatMap(WebSession::changeSessionId); } @Override public Mono<SecurityContext> load(ServerWebExchange exchange) { Mono<SecurityContext> result = exchange.getSession().flatMap((session) -> { SecurityContext context = (SecurityContext) session.getAttribute(this.springSecurityContextAttrName); logger.debug((context != null) ? LogMessage.format("Found SecurityContext '%s' in WebSession: '%s'", context, session) : LogMessage.format("No SecurityContext found in WebSession: '%s'", session)); return Mono.justOrEmpty(context); }); return (this.cacheSecurityContext) ? result.cache() : result; } }
3,894
38.744898
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/ReactorContextWebFilter.java
/* * Copyright 2002-2017 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.server.context; import reactor.core.publisher.Mono; import reactor.util.context.Context; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Uses a {@link ServerSecurityContextRepository} to provide the {@link SecurityContext} * to initialize the {@link ReactiveSecurityContextHolder}. * * @author Rob Winch * @since 5.0 */ public class ReactorContextWebFilter implements WebFilter { private final ServerSecurityContextRepository repository; public ReactorContextWebFilter(ServerSecurityContextRepository repository) { Assert.notNull(repository, "repository cannot be null"); this.repository = repository; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange).contextWrite( (context) -> context.hasKey(SecurityContext.class) ? context : withSecurityContext(context, exchange)); } private Context withSecurityContext(Context mainContext, ServerWebExchange exchange) { return mainContext.putAll( this.repository.load(exchange).as(ReactiveSecurityContextHolder::withSecurityContext).readOnly()); } }
2,064
35.22807
107
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/NoOpServerSecurityContextRepository.java
/* * Copyright 2002-2017 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.server.context; import reactor.core.publisher.Mono; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.server.ServerWebExchange; /** * A do nothing implementation of {@link ServerSecurityContextRepository}. Used in * stateless applications. * * @author Rob Winch * @since 5.0 */ public final class NoOpServerSecurityContextRepository implements ServerSecurityContextRepository { private static final NoOpServerSecurityContextRepository INSTANCE = new NoOpServerSecurityContextRepository(); private NoOpServerSecurityContextRepository() { } @Override public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) { return Mono.empty(); } @Override public Mono<SecurityContext> load(ServerWebExchange exchange) { return Mono.empty(); } public static NoOpServerSecurityContextRepository getInstance() { return INSTANCE; } }
1,577
28.773585
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/context/SecurityContextServerWebExchange.java
/* * Copyright 2002-2017 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.server.context; import java.security.Principal; import reactor.core.publisher.Mono; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchangeDecorator; /** * Overrides the {@link ServerWebExchange#getPrincipal()} with the provided * SecurityContext * * @author Rob Winch * @since 5.0 * @see SecurityContextServerWebExchangeWebFilter */ public class SecurityContextServerWebExchange extends ServerWebExchangeDecorator { private final Mono<SecurityContext> context; public SecurityContextServerWebExchange(ServerWebExchange delegate, Mono<SecurityContext> context) { super(delegate); this.context = context; } @Override @SuppressWarnings("unchecked") public <T extends Principal> Mono<T> getPrincipal() { return this.context.map((context) -> (T) context.getAuthentication()); } }
1,591
30.215686
101
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/jackson2/WebServerJackson2Module.java
/* * Copyright 2015-2018 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.server.jackson2; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.module.SimpleModule; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.web.server.csrf.DefaultCsrfToken; /** * Jackson module for spring-security-web-flux. This module register * {@link DefaultCsrfServerTokenMixin} If no default typing enabled by default then it'll * enable it because typing info is needed to properly serialize/deserialize objects. In * order to use this module just add this module into your ObjectMapper configuration. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebServerJackson2Module()); * </pre> <b>Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list * of all security modules.</b> * * @author Boris Finkelshteyn * @since 5.1 * @see SecurityJackson2Modules */ public class WebServerJackson2Module extends SimpleModule { private static final String NAME = WebServerJackson2Module.class.getName(); private static final Version VERSION = new Version(1, 0, 0, null, null, null); public WebServerJackson2Module() { super(NAME, VERSION); } @Override public void setupModule(SetupContext context) { SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); context.setMixInAnnotations(DefaultCsrfToken.class, DefaultCsrfServerTokenMixin.class); } }
2,100
35.224138
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/jackson2/DefaultCsrfServerTokenMixin.java
/* * Copyright 2015-2018 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.server.jackson2; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * Jackson mixin class to serialize/deserialize * {@link org.springframework.security.web.server.csrf.DefaultCsrfToken} serialization * support. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebServerJackson2Module()); * </pre> * * @author Boris Finkelshteyn * @since 5.1 * @see WebServerJackson2Module */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonIgnoreProperties(ignoreUnknown = true) class DefaultCsrfServerTokenMixin { /** * JsonCreator constructor needed by Jackson to create * {@link org.springframework.security.web.server.csrf.DefaultCsrfToken} object. * @param headerName the name of the header * @param parameterName the parameter name * @param token the CSRF token value */ @JsonCreator DefaultCsrfServerTokenMixin(@JsonProperty("headerName") String headerName, @JsonProperty("parameterName") String parameterName, @JsonProperty("token") String token) { } }
1,915
33.836364
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import java.util.function.Supplier; import reactor.core.publisher.Mono; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.server.ServerWebExchange; /** * Interface for writing headers just before the response is committed. * * @author Rob Winch * @since 5.0 */ public interface ServerHttpHeadersWriter { /** * Write the headers to the response. * @param exchange * @return A Mono which is returned to the {@link Supplier} of the * {@link ServerHttpResponse#beforeCommit(Supplier)}. */ Mono<Void> writeHttpHeaders(ServerWebExchange exchange); }
1,295
29.139535
75
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ClearSiteDataServerHttpHeadersWriter.java
/* * Copyright 2002-2019 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.server.header; import reactor.core.publisher.Mono; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * <p> * Writes the {@code Clear-Site-Data} response header when the request is secure. * </p> * * <p> * For further details pleaes consult <a href="https://www.w3.org/TR/clear-site-data/">W3C * Documentation</a>. * </p> * * @author MD Sayem Ahmed * @since 5.2 */ public final class ClearSiteDataServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; private final StaticServerHttpHeadersWriter headerWriterDelegate; /** * <p> * Constructs a new instance using the given directives. * </p> * @param directives directives that will be written as the header value * @throws IllegalArgumentException if the argument is null or empty */ public ClearSiteDataServerHttpHeadersWriter(Directive... directives) { Assert.notEmpty(directives, "directives cannot be empty or null"); this.headerWriterDelegate = StaticServerHttpHeadersWriter.builder() .header(CLEAR_SITE_DATA_HEADER, transformToHeaderValue(directives)).build(); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { if (isSecure(exchange)) { return this.headerWriterDelegate.writeHttpHeaders(exchange); } return Mono.empty(); } /** * <p> * Represents the directive values expected by the * {@link ClearSiteDataServerHttpHeadersWriter} * </p> * . */ public enum Directive { CACHE("cache"), COOKIES("cookies"), STORAGE("storage"), EXECUTION_CONTEXTS("executionContexts"), ALL("*"); private final String headerValue; Directive(String headerValue) { this.headerValue = "\"" + headerValue + "\""; } public String getHeaderValue() { return this.headerValue; } } private String transformToHeaderValue(Directive... directives) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); } private boolean isSecure(ServerWebExchange exchange) { String scheme = exchange.getRequest().getURI().getScheme(); return scheme != null && scheme.equalsIgnoreCase("https"); } }
3,024
26.5
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/FeaturePolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2018 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Writes the {@code Feature-Policy} response header with configured policy directives. * * @author Vedran Pavic * @since 5.1 */ public final class FeaturePolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String FEATURE_POLICY = "Feature-Policy"; private ServerHttpHeadersWriter delegate; @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } /** * Set the policy directive(s) to be used in the response header. * @param policyDirectives the policy directive(s) * @throws IllegalArgumentException if policyDirectives is {@code null} or empty */ public void setPolicyDirectives(String policyDirectives) { Assert.hasLength(policyDirectives, "policyDirectives must not be null or empty"); this.delegate = createDelegate(policyDirectives); } private static ServerHttpHeadersWriter createDelegate(String policyDirectives) { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(FEATURE_POLICY, policyDirectives); return builder.build(); } }
2,058
33.898305
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ServerWebExchangeDelegatingServerHttpHeadersWriter.java
/* * Copyright 2002-2022 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Delegates to a provided {@link ServerHttpHeadersWriter} if * {@link ServerWebExchangeMatcher#matches(ServerWebExchange)} returns a match. * * @author David Herberth * @since 5.8 */ public final class ServerWebExchangeDelegatingServerHttpHeadersWriter implements ServerHttpHeadersWriter { private final ServerWebExchangeMatcherEntry<ServerHttpHeadersWriter> headersWriter; /** * Creates a new instance * @param headersWriter the {@link ServerWebExchangeMatcherEntry} holding a * {@link ServerWebExchangeMatcher} and the {@link ServerHttpHeadersWriter} to invoke * if the matcher returns a match. */ public ServerWebExchangeDelegatingServerHttpHeadersWriter( ServerWebExchangeMatcherEntry<ServerHttpHeadersWriter> headersWriter) { Assert.notNull(headersWriter, "headersWriter cannot be null"); Assert.notNull(headersWriter.getMatcher(), "webExchangeMatcher cannot be null"); Assert.notNull(headersWriter.getEntry(), "delegateHeadersWriter cannot be null"); this.headersWriter = headersWriter; } /** * Creates a new instance * @param webExchangeMatcher the {@link ServerWebExchangeMatcher} to use. If it * returns a match, the delegateHeadersWriter is invoked. * @param delegateHeadersWriter the {@link ServerHttpHeadersWriter} to invoke if the * {@link ServerWebExchangeMatcher} returns a match. */ public ServerWebExchangeDelegatingServerHttpHeadersWriter(ServerWebExchangeMatcher webExchangeMatcher, ServerHttpHeadersWriter delegateHeadersWriter) { this(new ServerWebExchangeMatcherEntry<>(webExchangeMatcher, delegateHeadersWriter)); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.headersWriter.getMatcher().matches(exchange).filter(ServerWebExchangeMatcher.MatchResult::isMatch) .flatMap((matchResult) -> this.headersWriter.getEntry().writeHttpHeaders(exchange)); } }
2,875
40.085714
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ContentSecurityPolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2018 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Writes the {@code Contet-Security-Policy} response header with configured policy * directives. * * @author Vedran Pavic * @since 5.1 */ public final class ContentSecurityPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; private String policyDirectives; private boolean reportOnly; private ServerHttpHeadersWriter delegate; @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } /** * Set the policy directive(s) to be used in the response header. * @param policyDirectives the policy directive(s) * @throws IllegalArgumentException if policyDirectives is {@code null} or empty */ public void setPolicyDirectives(String policyDirectives) { Assert.hasLength(policyDirectives, "policyDirectives must not be null or empty"); this.policyDirectives = policyDirectives; this.delegate = createDelegate(); } /** * Set whether to include the {@code Content-Security-Policy-Report-Only} header in * the response. Otherwise, defaults to the {@code Content-Security-Policy} header. * @param reportOnly whether to only report policy violations */ public void setReportOnly(boolean reportOnly) { this.reportOnly = reportOnly; this.delegate = createDelegate(); } private ServerHttpHeadersWriter createDelegate() { if (this.policyDirectives == null) { return null; } Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(resolveHeader(this.reportOnly), this.policyDirectives); return builder.build(); } private static String resolveHeader(boolean reportOnly) { return reportOnly ? CONTENT_SECURITY_POLICY_REPORT_ONLY : CONTENT_SECURITY_POLICY; } }
2,856
33.011905
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/XXssProtectionServerHttpHeadersWriter.java
/* * Copyright 2002-2022 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Add the x-xss-protection header. * * @author Rob Winch * @author Daniel Garnier-Moiroux * @since 5.0 */ public class XXssProtectionServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String X_XSS_PROTECTION = "X-XSS-Protection"; private ServerHttpHeadersWriter delegate; private HeaderValue headerValue; /** * Creates a new instance */ public XXssProtectionServerHttpHeadersWriter() { this.headerValue = HeaderValue.DISABLED; updateDelegate(); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.delegate.writeHttpHeaders(exchange); } /** * Sets the value of the X-XSS-PROTECTION header. Defaults to * {@link HeaderValue#DISABLED} * <p> * If {@link HeaderValue#DISABLED}, will specify that X-XSS-Protection is disabled. * For example: * * <pre> * X-XSS-Protection: 0 * </pre> * <p> * If {@link HeaderValue#ENABLED}, will contain a value of 1, but will not specify the * mode as blocked. In this instance, any content will be attempted to be fixed. For * example: * * <pre> * X-XSS-Protection: 1 * </pre> * <p> * If {@link HeaderValue#ENABLED_MODE_BLOCK}, will contain a value of 1 and will * specify mode as blocked. The content will be replaced with "#". For example: * * <pre> * X-XSS-Protection: 1 ; mode=block * </pre> * @param headerValue the new headerValue * @throws IllegalArgumentException if headerValue is null * @since 5.8 */ public void setHeaderValue(HeaderValue headerValue) { Assert.notNull(headerValue, "headerValue cannot be null"); this.headerValue = headerValue; updateDelegate(); } /** * The value of the x-xss-protection header. One of: "0", "1", "1 ; mode=block" * * @author Daniel Garnier-Moiroux * @since 5.8 */ public enum HeaderValue { DISABLED("0"), ENABLED("1"), ENABLED_MODE_BLOCK("1 ; mode=block"); private final String value; HeaderValue(String value) { this.value = value; } @Override public String toString() { return this.value; } } private void updateDelegate() { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(X_XSS_PROTECTION, this.headerValue.toString()); this.delegate = builder.build(); } }
3,184
25.991525
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/PermissionsPolicyServerHttpHeadersWriter.java
/* * 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Writes the {@code Permissions-Policy} response header with configured policy * directives. * * @author Christophe Gilles * @since 5.5 */ public final class PermissionsPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String PERMISSIONS_POLICY = "Permissions-Policy"; private ServerHttpHeadersWriter delegate; @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(String policyDirectives) { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(PERMISSIONS_POLICY, policyDirectives); return builder.build(); } /** * Set the policy to be used in the response header. * @param policy the policy * @throws IllegalArgumentException if policy is {@code null} */ public void setPolicy(String policy) { Assert.notNull(policy, "policy must not be null"); this.delegate = createDelegate(policy); } }
1,970
31.85
96
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import java.util.Arrays; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * Combines multiple {@link ServerHttpHeadersWriter} instances into a single instance. * * @author Rob Winch * @since 5.0 */ public class CompositeServerHttpHeadersWriter implements ServerHttpHeadersWriter { private final List<ServerHttpHeadersWriter> writers; public CompositeServerHttpHeadersWriter(ServerHttpHeadersWriter... writers) { this(Arrays.asList(writers)); } public CompositeServerHttpHeadersWriter(List<ServerHttpHeadersWriter> writers) { this.writers = writers; } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return Flux.fromIterable(this.writers).concatMap((w) -> w.writeHttpHeaders(exchange)).then(); } }
1,538
29.176471
95
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriter.java
/* * Copyright 2002-2021 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.server.header; import java.util.Arrays; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.web.server.ServerWebExchange; /** * Allows specifying {@link HttpHeaders} that should be written to the response. * * @author Rob Winch * @since 5.0 */ public class StaticServerHttpHeadersWriter implements ServerHttpHeadersWriter { private final HttpHeaders headersToAdd; public StaticServerHttpHeadersWriter(HttpHeaders headersToAdd) { this.headersToAdd = headersToAdd; } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { HttpHeaders headers = exchange.getResponse().getHeaders(); // Note: We need to ensure that the following algorithm compares headers // case insensitively, which should be true of headers.containsKey(). boolean containsNoHeadersToAdd = true; for (String headerName : this.headersToAdd.keySet()) { if (headers.containsKey(headerName)) { containsNoHeadersToAdd = false; break; } } if (containsNoHeadersToAdd) { this.headersToAdd.forEach(headers::put); } return Mono.empty(); } public static Builder builder() { return new Builder(); } public static class Builder { private HttpHeaders headers = new HttpHeaders(); public Builder header(String headerName, String... values) { this.headers.put(headerName, Arrays.asList(values)); return this; } public StaticServerHttpHeadersWriter build() { return new StaticServerHttpHeadersWriter(this.headers); } } }
2,196
27.166667
80
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/StrictTransportSecurityServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import java.time.Duration; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.web.server.ServerWebExchange; /** * Writes the Strict-Transport-Security if the request is secure. * * @author Rob Winch * @author Ankur Pathak * @since 5.0 */ public final class StrictTransportSecurityServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; private String maxAge; private String subdomain; private String preload; private ServerHttpHeadersWriter delegate; public StrictTransportSecurityServerHttpHeadersWriter() { setIncludeSubDomains(true); setMaxAge(Duration.ofDays(365L)); setPreload(false); updateDelegate(); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return isSecure(exchange) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } /** * Sets if subdomains should be included. Default is true * @param includeSubDomains if subdomains should be included */ public void setIncludeSubDomains(boolean includeSubDomains) { this.subdomain = includeSubDomains ? " ; includeSubDomains" : ""; updateDelegate(); } /** * <p> * Sets if preload should be included. Default is false * </p> * * <p> * See <a href="https://hstspreload.org/">Website hstspreload.org</a> for additional * details. * </p> * @param preload if preload should be included * @since 5.2.0 */ public void setPreload(boolean preload) { this.preload = preload ? " ; preload" : ""; updateDelegate(); } /** * Sets the max age of the header. Default is a year. * @param maxAge the max age of the header */ public void setMaxAge(Duration maxAge) { this.maxAge = "max-age=" + maxAge.getSeconds(); updateDelegate(); } private void updateDelegate() { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(STRICT_TRANSPORT_SECURITY, this.maxAge + this.subdomain + this.preload); this.delegate = builder.build(); } private boolean isSecure(ServerWebExchange exchange) { String scheme = exchange.getRequest().getURI().getScheme(); boolean isSecure = scheme != null && scheme.equalsIgnoreCase("https"); return isSecure; } }
3,016
27.733333
102
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ContentTypeOptionsServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * Adds X-Content-Type-Options: nosniff * * @author Rob Winch * @since 5.0 */ public class ContentTypeOptionsServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String X_CONTENT_OPTIONS = "X-Content-Type-Options"; public static final String NOSNIFF = "nosniff"; /** * The delegate to write all the cache control related headers */ private static final ServerHttpHeadersWriter CONTENT_TYPE_HEADERS = StaticServerHttpHeadersWriter.builder() .header(X_CONTENT_OPTIONS, NOSNIFF).build(); @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return CONTENT_TYPE_HEADERS.writeHttpHeaders(exchange); } }
1,452
29.914894
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/CacheControlServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; /** * Writes cache control related headers. * * <pre> * Cache-Control: no-cache, no-store, max-age=0, must-revalidate * Pragma: no-cache * Expires: 0 * </pre> * * @author Rob Winch * @since 5.0 */ public class CacheControlServerHttpHeadersWriter implements ServerHttpHeadersWriter { /** * The value for expires value */ public static final String EXPIRES_VALUE = "0"; /** * The value for pragma value */ public static final String PRAGMA_VALUE = "no-cache"; /** * The value for cache control value */ public static final String CACHE_CONTRTOL_VALUE = "no-cache, no-store, max-age=0, must-revalidate"; /** * The delegate to write all the cache control related headers */ private static final ServerHttpHeadersWriter CACHE_HEADERS = StaticServerHttpHeadersWriter.builder() .header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE) .header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE) .header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE).build(); @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { if (exchange.getResponse().getStatusCode() == HttpStatus.NOT_MODIFIED) { return Mono.empty(); } return CACHE_HEADERS.writeHttpHeaders(exchange); } }
2,181
29.732394
101
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2021 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.server.header; import reactor.core.publisher.Mono; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Inserts Cross-Origin-Embedder-Policy headers. * * @author Marcus Da Coregio * @since 5.7 * @see <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy"> * Cross-Origin-Embedder-Policy</a> */ public final class CrossOriginEmbedderPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; private ServerHttpHeadersWriter delegate; /** * Sets the {@link CrossOriginEmbedderPolicy} value to be used in the * {@code Cross-Origin-Embedder-Policy} header * @param embedderPolicy the {@link CrossOriginEmbedderPolicy} to use */ public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) { Assert.notNull(embedderPolicy, "embedderPolicy cannot be null"); this.delegate = createDelegate(embedderPolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginEmbedderPolicy embedderPolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(EMBEDDER_POLICY, embedderPolicy.getPolicy()); return builder.build(); } public enum CrossOriginEmbedderPolicy { UNSAFE_NONE("unsafe-none"), REQUIRE_CORP("require-corp"); private final String policy; CrossOriginEmbedderPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
2,414
29.56962
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/XFrameOptionsServerHttpHeadersWriter.java
/* * Copyright 2002-2017 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.server.header; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.web.server.ServerWebExchange; /** * {@code ServerHttpHeadersWriter} implementation for the X-Frame-Options headers. * * @author Rob Winch * @since 5.0 */ public class XFrameOptionsServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String X_FRAME_OPTIONS = "X-Frame-Options"; private ServerHttpHeadersWriter delegate = createDelegate(Mode.DENY); @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.delegate.writeHttpHeaders(exchange); } /** * Sets the X-Frame-Options mode. There is no support for ALLOW-FROM because not * <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">all * browsers support it</a>. Consider using X-Frame-Options with * Content-Security-Policy <a href= * "https://w3c.github.io/webappsec/specs/content-security-policy/#directive-frame-ancestors">frame-ancestors</a>. * @param mode */ public void setMode(Mode mode) { this.delegate = createDelegate(mode); } /** * The X-Frame-Options values. There is no support for ALLOW-FROM because not <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">all * browsers support it</a>. Consider using X-Frame-Options with * Content-Security-Policy <a href= * "https://w3c.github.io/webappsec/specs/content-security-policy/#directive-frame-ancestors">frame-ancestors</a>. * * @author Rob Winch * @since 5.0 */ public enum Mode { /** * A browser receiving content with this header field MUST NOT display this * content in any frame. */ DENY, /** * A browser receiving content with this header field MUST NOT display this * content in any frame from a page of different origin than the content itself. * * If a browser or plugin cannot reliably determine whether or not the origin of * the content and the frame are the same, this MUST be treated as "DENY". */ SAMEORIGIN } private static ServerHttpHeadersWriter createDelegate(Mode mode) { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(X_FRAME_OPTIONS, mode.name()); return builder.build(); } }
3,010
32.087912
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/ReferrerPolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2018 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.server.header; import java.util.Collections; import java.util.HashMap; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.security.web.server.header.StaticServerHttpHeadersWriter.Builder; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Writes the {@code Referrer-Policy} response header. * * @author Vedran Pavic * @since 5.1 */ public final class ReferrerPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String REFERRER_POLICY = "Referrer-Policy"; private ServerHttpHeadersWriter delegate; public ReferrerPolicyServerHttpHeadersWriter() { this.delegate = createDelegate(ReferrerPolicy.NO_REFERRER); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.delegate.writeHttpHeaders(exchange); } /** * Set the policy to be used in the response header. * @param policy the policy * @throws IllegalArgumentException if policy is {@code null} */ public void setPolicy(ReferrerPolicy policy) { Assert.notNull(policy, "policy must not be null"); this.delegate = createDelegate(policy); } private static ServerHttpHeadersWriter createDelegate(ReferrerPolicy policy) { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(REFERRER_POLICY, policy.getPolicy()); return builder.build(); } public enum ReferrerPolicy { NO_REFERRER("no-referrer"), NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"), SAME_ORIGIN("same-origin"), ORIGIN("origin"), STRICT_ORIGIN("strict-origin"), ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"), STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"), UNSAFE_URL("unsafe-url"); private static final Map<String, ReferrerPolicy> REFERRER_POLICIES; static { Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>(); for (ReferrerPolicy referrerPolicy : values()) { referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy); } REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies); } private final String policy; ReferrerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
2,951
26.588785
93
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2021 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.server.header; import reactor.core.publisher.Mono; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Inserts Cross-Origin-Opener-Policy header. * * @author Marcus Da Coregio * @since 5.7 * @see <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy"> * Cross-Origin-Opener-Policy</a> */ public final class CrossOriginOpenerPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String OPENER_POLICY = "Cross-Origin-Opener-Policy"; private ServerHttpHeadersWriter delegate; /** * Sets the {@link CrossOriginOpenerPolicy} value to be used in the * {@code Cross-Origin-Opener-Policy} header * @param openerPolicy the {@link CrossOriginOpenerPolicy} to use */ public void setPolicy(CrossOriginOpenerPolicy openerPolicy) { Assert.notNull(openerPolicy, "openerPolicy cannot be null"); this.delegate = createDelegate(openerPolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginOpenerPolicy openerPolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(OPENER_POLICY, openerPolicy.getPolicy()); return builder.build(); } public enum CrossOriginOpenerPolicy { UNSAFE_NONE("unsafe-none"), SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"), SAME_ORIGIN("same-origin"); private final String policy; CrossOriginOpenerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
2,426
28.962963
102
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriter.java
/* * Copyright 2002-2021 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.server.header; import reactor.core.publisher.Mono; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Inserts Cross-Origin-Resource-Policy headers. * * @author Marcus Da Coregio * @since 5.7 * @see <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy"> * Cross-Origin-Resource-Policy</a> */ public final class CrossOriginResourcePolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; private ServerHttpHeadersWriter delegate; /** * Sets the {@link CrossOriginResourcePolicy} value to be used in the * {@code Cross-Origin-Embedder-Policy} header * @param resourcePolicy the {@link CrossOriginResourcePolicy} to use */ public void setPolicy(CrossOriginResourcePolicy resourcePolicy) { Assert.notNull(resourcePolicy, "resourcePolicy cannot be null"); this.delegate = createDelegate(resourcePolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginResourcePolicy resourcePolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(RESOURCE_POLICY, resourcePolicy.getPolicy()); return builder.build(); } public enum CrossOriginResourcePolicy { SAME_SITE("same-site"), SAME_ORIGIN("same-origin"), CROSS_ORIGIN("cross-origin"); private final String policy; CrossOriginResourcePolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
2,441
29.148148
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilter.java
/* * Copyright 2002-2017 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.server.header; import reactor.core.publisher.Mono; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Invokes a {@link ServerHttpHeadersWriter} on * {@link ServerHttpResponse#beforeCommit(java.util.function.Supplier)}. * * @author Rob Winch * @since 5.0 */ public class HttpHeaderWriterWebFilter implements WebFilter { private final ServerHttpHeadersWriter writer; public HttpHeaderWriterWebFilter(ServerHttpHeadersWriter writer) { this.writer = writer; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { exchange.getResponse().beforeCommit(() -> this.writer.writeHttpHeaders(exchange)); return chain.filter(exchange); } }
1,533
30.958333
84
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/header/XContentTypeOptionsServerHttpHeadersWriter.java
/* * Copyright 2002-2023 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.server.header; import reactor.core.publisher.Mono; import org.springframework.web.server.ServerWebExchange; /** * Adds X-Content-Type-Options: nosniff * * @author Rob Winch * @since 5.0 */ public class XContentTypeOptionsServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String X_CONTENT_OPTIONS = "X-Content-Type-Options"; public static final String NOSNIFF = "nosniff"; /** * The delegate to write all the cache control related headers */ private static final ServerHttpHeadersWriter CONTENT_TYPE_HEADERS = StaticServerHttpHeadersWriter.builder() .header(X_CONTENT_OPTIONS, NOSNIFF).build(); @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return CONTENT_TYPE_HEADERS.writeHttpHeaders(exchange); } }
1,453
29.93617
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcher.java
/* * 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Matches if the {@link ServerAuthenticationConverter} can convert a * {@link ServerWebExchange} to an {@link Authentication}. * * @author David Kovac * @since 5.4 * @see ServerAuthenticationConverter */ public final class AuthenticationConverterServerWebExchangeMatcher implements ServerWebExchangeMatcher { private final ServerAuthenticationConverter serverAuthenticationConverter; public AuthenticationConverterServerWebExchangeMatcher( ServerAuthenticationConverter serverAuthenticationConverter) { Assert.notNull(serverAuthenticationConverter, "serverAuthenticationConverter cannot be null"); this.serverAuthenticationConverter = serverAuthenticationConverter; } @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return this.serverAuthenticationConverter.convert(exchange).flatMap((a) -> MatchResult.match()) .onErrorResume((ex) -> MatchResult.notMatch()).switchIfEmpty(MatchResult.notMatch()); } }
1,927
36.803922
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.java
/* * Copyright 2002-2022 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.server.authentication; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.web.access.intercept.RequestMatcherDelegatingAuthorizationManager; import org.springframework.security.web.authentication.RequestMatcherDelegatingAuthenticationManagerResolver; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * A {@link ReactiveAuthenticationManagerResolver} that returns a * {@link ReactiveAuthenticationManager} instances based upon the type of * {@link ServerWebExchange} passed into {@link #resolve(ServerWebExchange)}. * * @author Josh Cummings * @since 5.7 * */ public final class ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver implements ReactiveAuthenticationManagerResolver<ServerWebExchange> { private final List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> authenticationManagers; private ReactiveAuthenticationManager defaultAuthenticationManager = (authentication) -> Mono .error(new AuthenticationServiceException("Cannot authenticate " + authentication)); /** * Construct an * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} based on * the provided parameters * @param managers a set of {@link ServerWebExchangeMatcherEntry}s */ ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver( ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>... managers) { this(Arrays.asList(managers)); } /** * Construct an * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} based on * the provided parameters * @param managers a {@link List} of {@link ServerWebExchangeMatcherEntry}s */ ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver( List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> managers) { Assert.notNull(managers, "entries cannot be null"); this.authenticationManagers = managers; } /** * {@inheritDoc} */ @Override public Mono<ReactiveAuthenticationManager> resolve(ServerWebExchange exchange) { return Flux.fromIterable(this.authenticationManagers).filterWhen((entry) -> isMatch(exchange, entry)).next() .map(ServerWebExchangeMatcherEntry::getEntry).defaultIfEmpty(this.defaultAuthenticationManager); } /** * Set the default {@link ReactiveAuthenticationManager} to use when a request does * not match * @param defaultAuthenticationManager the default * {@link ReactiveAuthenticationManager} to use */ public void setDefaultAuthenticationManager(ReactiveAuthenticationManager defaultAuthenticationManager) { Assert.notNull(defaultAuthenticationManager, "defaultAuthenticationManager cannot be null"); this.defaultAuthenticationManager = defaultAuthenticationManager; } /** * Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}. * @return the new {@link RequestMatcherDelegatingAuthorizationManager.Builder} * instance */ public static Builder builder() { return new Builder(); } private Mono<Boolean> isMatch(ServerWebExchange exchange, ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager> entry) { ServerWebExchangeMatcher matcher = entry.getMatcher(); return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch); } /** * A builder for {@link RequestMatcherDelegatingAuthenticationManagerResolver}. */ public static final class Builder { private final List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> entries = new ArrayList<>(); private Builder() { } /** * Maps a {@link ServerWebExchangeMatcher} to an * {@link ReactiveAuthenticationManager}. * @param matcher the {@link ServerWebExchangeMatcher} to use * @param manager the {@link ReactiveAuthenticationManager} to use * @return the * {@link RequestMatcherDelegatingAuthenticationManagerResolver.Builder} for * further customizations */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder add( ServerWebExchangeMatcher matcher, ReactiveAuthenticationManager manager) { Assert.notNull(matcher, "matcher cannot be null"); Assert.notNull(manager, "manager cannot be null"); this.entries.add(new ServerWebExchangeMatcherEntry<>(matcher, manager)); return this; } /** * Creates a {@link RequestMatcherDelegatingAuthenticationManagerResolver} * instance. * @return the {@link RequestMatcherDelegatingAuthenticationManagerResolver} * instance */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver build() { return new ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver(this.entries); } } }
5,898
37.809211
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandler.java
/* * Copyright 2002-2017 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.server.authentication; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Performs a redirect to a specified location. * * @author Rob Winch * @since 5.0 */ public class RedirectServerAuthenticationFailureHandler implements ServerAuthenticationFailureHandler { private final URI location; private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); /** * Creates an instance * @param location the location to redirect to (i.e. "/login?failed") */ public RedirectServerAuthenticationFailureHandler(String location) { Assert.notNull(location, "location cannot be null"); this.location = URI.create(location); } /** * Sets the RedirectStrategy to use. * @param redirectStrategy the strategy to use. Default is DefaultRedirectStrategy. */ public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } @Override public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) { return this.redirectStrategy.sendRedirect(webFilterExchange.getExchange(), this.location); } }
2,216
33.107692
116
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandler.java
/* * Copyright 2002-2017 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.server.authentication; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.savedrequest.ServerRequestCache; import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Performs a redirect on authentication success. The default is to redirect to a saved * request if present and otherwise "/". * * @author Rob Winch * @since 5.0 */ public class RedirectServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler { private URI location = URI.create("/"); private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); private ServerRequestCache requestCache = new WebSessionServerRequestCache(); /** * Creates a new instance with location of "/" */ public RedirectServerAuthenticationSuccessHandler() { } /** * Creates a new instance with the specified location * @param location the location to redirect if the no request is cached in * {@link #setRequestCache(ServerRequestCache)} */ public RedirectServerAuthenticationSuccessHandler(String location) { this.location = URI.create(location); } /** * Sets the {@link ServerRequestCache} used to redirect to. Default is * {@link WebSessionServerRequestCache}. * @param requestCache the cache to use */ public void setRequestCache(ServerRequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { ServerWebExchange exchange = webFilterExchange.getExchange(); return this.requestCache.getRedirectUri(exchange).defaultIfEmpty(this.location) .flatMap((location) -> this.redirectStrategy.sendRedirect(exchange, location)); } /** * Where the user is redirected to upon authentication success * @param location the location to redirect to. The default is "/" */ public void setLocation(URI location) { Assert.notNull(location, "location cannot be null"); this.location = location; } /** * The RedirectStrategy to use. * @param redirectStrategy the strategy to use. Default is DefaultRedirectStrategy. */ public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } }
3,484
34.561224
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandler.java
/* * Copyright 2002-2018 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.server.authentication; import java.util.Arrays; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Delegates to a collection of {@link ServerAuthenticationSuccessHandler} * implementations. * * @author Rob Winch * @since 5.1 */ public class DelegatingServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler { private final List<ServerAuthenticationSuccessHandler> delegates; public DelegatingServerAuthenticationSuccessHandler(ServerAuthenticationSuccessHandler... delegates) { Assert.notEmpty(delegates, "delegates cannot be null or empty"); this.delegates = Arrays.asList(delegates); } @Override public Mono<Void> onAuthenticationSuccess(WebFilterExchange exchange, Authentication authentication) { return Flux.fromIterable(this.delegates) .concatMap((delegate) -> delegate.onAuthenticationSuccess(exchange, authentication)).then(); } }
1,771
33.076923
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverter.java
/* * Copyright 2002-2018 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.server.authentication; import java.security.cert.X509Certificate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.http.server.reactive.SslInfo; import org.springframework.lang.NonNull; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor; import org.springframework.web.server.ServerWebExchange; /** * Converts from a {@link SslInfo} provided by a request to an * {@link PreAuthenticatedAuthenticationToken} that can be authenticated. * * @author Alexey Nesterov * @since 5.2 */ public class ServerX509AuthenticationConverter implements ServerAuthenticationConverter { protected final Log logger = LogFactory.getLog(getClass()); private final X509PrincipalExtractor principalExtractor; public ServerX509AuthenticationConverter(@NonNull X509PrincipalExtractor principalExtractor) { this.principalExtractor = principalExtractor; } @Override public Mono<Authentication> convert(ServerWebExchange exchange) { SslInfo sslInfo = exchange.getRequest().getSslInfo(); if (sslInfo == null) { this.logger.debug("No SslInfo provided with a request, skipping x509 authentication"); return Mono.empty(); } if (sslInfo.getPeerCertificates() == null || sslInfo.getPeerCertificates().length == 0) { this.logger.debug("No peer certificates found in SslInfo, skipping x509 authentication"); return Mono.empty(); } X509Certificate clientCertificate = sslInfo.getPeerCertificates()[0]; Object principal = this.principalExtractor.extractPrincipal(clientCertificate); return Mono.just(new PreAuthenticatedAuthenticationToken(principal, clientCertificate)); } }
2,549
37.636364
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManager.java
/* * Copyright 2002-2019 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** * Reactive version of * {@link org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider} * * This manager receives a {@link PreAuthenticatedAuthenticationToken}, checks that * associated account is not disabled, expired, or blocked, and returns new authenticated * {@link PreAuthenticatedAuthenticationToken}. * * If no {@link UserDetailsChecker} is provided, a default * {@link AccountStatusUserDetailsChecker} will be created. * * @author Alexey Nesterov * @since 5.2 */ public class ReactivePreAuthenticatedAuthenticationManager implements ReactiveAuthenticationManager { private final ReactiveUserDetailsService userDetailsService; private final UserDetailsChecker userDetailsChecker; public ReactivePreAuthenticatedAuthenticationManager(ReactiveUserDetailsService userDetailsService) { this(userDetailsService, new AccountStatusUserDetailsChecker()); } public ReactivePreAuthenticatedAuthenticationManager(ReactiveUserDetailsService userDetailsService, UserDetailsChecker userDetailsChecker) { this.userDetailsService = userDetailsService; this.userDetailsChecker = userDetailsChecker; } @Override public Mono<Authentication> authenticate(Authentication authentication) { return Mono.just(authentication).filter(this::supports).map(Authentication::getName) .flatMap(this.userDetailsService::findByUsername) .switchIfEmpty(Mono.error(() -> new UsernameNotFoundException("User not found"))) .doOnNext(this.userDetailsChecker::check).map((userDetails) -> { PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities()); result.setDetails(authentication.getDetails()); return result; }); } private boolean supports(Authentication authentication) { return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication.getClass()); } }
3,253
41.25974
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationSuccessHandler.java
/* * Copyright 2002-2017 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; /** * Handles authentication success * * @author Rob Winch * @since 5.0 */ public interface ServerAuthenticationSuccessHandler { /** * Invoked when the application authenticates successfully * @param webFilterExchange the exchange * @param authentication the {@link Authentication} * @return a completion notification (success or error) */ Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication); }
1,314
31.073171
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/AnonymousAuthenticationWebFilter.java
/* * 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.server.authentication; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Detects if there is no {@code Authentication} object in the * {@code ReactiveSecurityContextHolder}, and populates it with one if needed. * * @author Ankur Pathak * @author Mathieu Ouellet * @since 5.2.0 */ public class AnonymousAuthenticationWebFilter implements WebFilter { private static final Log logger = LogFactory.getLog(AnonymousAuthenticationWebFilter.class); private String key; private Object principal; private List<GrantedAuthority> authorities; /** * Creates a filter with a principal named "anonymousUser" and the single authority * "ROLE_ANONYMOUS". * @param key the key to identify tokens created by this filter */ public AnonymousAuthenticationWebFilter(String key) { this(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); } /** * @param key key the key to identify tokens created by this filter * @param principal the principal which will be used to represent anonymous users * @param authorities the authority list for anonymous users */ public AnonymousAuthenticationWebFilter(String key, Object principal, List<GrantedAuthority> authorities) { Assert.hasLength(key, "key cannot be null or empty"); Assert.notNull(principal, "Anonymous authentication principal must be set"); Assert.notNull(authorities, "Anonymous authorities must be set"); this.key = key; this.principal = principal; this.authorities = authorities; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return ReactiveSecurityContextHolder.getContext().switchIfEmpty(Mono.defer(() -> { Authentication authentication = createAuthentication(exchange); SecurityContext securityContext = new SecurityContextImpl(authentication); logger.debug(LogMessage.format("Populated SecurityContext with anonymous token: '%s'", authentication)); return chain.filter(exchange) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) .then(Mono.empty()); })).flatMap((securityContext) -> { logger.debug(LogMessage.format("SecurityContext contains anonymous token: '%s'", securityContext.getAuthentication())); return chain.filter(exchange); }); } protected Authentication createAuthentication(ServerWebExchange exchange) { return new AnonymousAuthenticationToken(this.key, this.principal, this.authorities); } }
3,954
38.55
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/WebFilterChainServerAuthenticationSuccessHandler.java
/* * Copyright 2002-2017 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.ServerWebExchange; /** * Success handler that continues the filter chain after authentication success. * * @author Rob Winch * @since 5.0 */ public class WebFilterChainServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler { @Override public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { ServerWebExchange exchange = webFilterExchange.getExchange(); return webFilterExchange.getChain().filter(exchange); } }
1,394
33.875
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationConverter.java
/* * Copyright 2002-2018 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.web.server.ServerWebExchange; /** * A strategy used for converting from a {@link ServerWebExchange} to an * {@link Authentication} used for authenticating with a provided * {@link org.springframework.security.authentication.ReactiveAuthenticationManager}. If * the result is {@link Mono#empty()}, then it signals that no authentication attempt * should be made. * * @author Eric Deandrea * @since 5.1 */ @FunctionalInterface public interface ServerAuthenticationConverter { /** * Converts a {@link ServerWebExchange} to an {@link Authentication} * @param exchange The {@link ServerWebExchange} * @return A {@link Mono} representing an {@link Authentication} */ Mono<Authentication> convert(ServerWebExchange exchange); }
1,552
33.511111
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationFailureHandler.java
/* * Copyright 2002-2017 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.WebFilterExchange; /** * Handles authentication failure * * @author Rob Winch * @since 5.0 */ public interface ServerAuthenticationFailureHandler { /** * Invoked when authentication attempt fails * @param webFilterExchange the exchange * @param exception the reason authentication failed * @return a completion notification (success or error) */ Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception); }
1,314
31.073171
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPoint.java
/* * Copyright 2002-2017 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.server.authentication; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.savedrequest.ServerRequestCache; import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Performs a redirect to a specified location. * * @author Rob Winch * @since 5.0 */ public class RedirectServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint { private final URI location; private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); private ServerRequestCache requestCache = new WebSessionServerRequestCache(); /** * Creates an instance * @param location the location to redirect to (i.e. "/logout-success") */ public RedirectServerAuthenticationEntryPoint(String location) { Assert.notNull(location, "location cannot be null"); this.location = URI.create(location); } /** * The request cache to use to save the request before sending a redirect. * @param requestCache the cache to redirect to. */ public void setRequestCache(ServerRequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) { return this.requestCache.saveRequest(exchange) .then(this.redirectStrategy.sendRedirect(exchange, this.location)); } /** * Sets the RedirectStrategy to use. * @param redirectStrategy the strategy to use. Default is DefaultRedirectStrategy. */ public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } }
2,826
34.3375
95
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/SwitchUserWebFilter.java
/* * Copyright 2002-2022 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.server.authentication; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.http.HttpMethod; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Switch User processing filter responsible for user context switching. A common use-case * for this feature is the ability to allow higher-authority users (e.g. ROLE_ADMIN) to * switch to a regular user (e.g. ROLE_USER). * <p> * This filter assumes that the user performing the switch will be required to be logged * in as normal user (i.e. with a ROLE_ADMIN role). The user will then access a * page/controller that enables the administrator to specify who they wish to become (see * <code>switchUserUrl</code>). * <p> * <b>Note: This URL will be required to have appropriate security constraints configured * so that only users of that role can access it (e.g. ROLE_ADMIN).</b> * <p> * On a successful switch, the user's <code>SecurityContext</code> will be updated to * reflect the specified user and will also contain an additional * {@link org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority} * which contains the original user. Before switching, a check will be made on whether the * user is already currently switched, and any current switch will be exited to prevent * "nested" switches. * <p> * To 'exit' from a user context, the user needs to access a URL (see * <code>exitUserUrl</code>) that will switch back to the original user as identified by * the <code>ROLE_PREVIOUS_ADMINISTRATOR</code>. * <p> * To configure the Switch User Processing Filter, create a bean definition for the Switch * User processing filter and add to the filterChainProxy. Note that the filter must come * <b>after</b> the * {@link org.springframework.security.config.web.server.SecurityWebFiltersOrder#AUTHORIZATION} * in the chain, in order to apply the correct constraints to the <tt>switchUserUrl</tt>. * Example: <pre> * SwitchUserWebFilter filter = new SwitchUserWebFilter(userDetailsService, loginSuccessHandler, failureHandler); * http.addFilterAfter(filter, SecurityWebFiltersOrder.AUTHORIZATION); * </pre> * * @author Artur Otrzonsek * @since 5.4 * @see SwitchUserGrantedAuthority */ public class SwitchUserWebFilter implements WebFilter { private final Log logger = LogFactory.getLog(getClass()); public static final String SPRING_SECURITY_SWITCH_USERNAME_KEY = "username"; public static final String ROLE_PREVIOUS_ADMINISTRATOR = "ROLE_PREVIOUS_ADMINISTRATOR"; private final ServerAuthenticationSuccessHandler successHandler; private final ServerAuthenticationFailureHandler failureHandler; private final ReactiveUserDetailsService userDetailsService; private final UserDetailsChecker userDetailsChecker; private ServerSecurityContextRepository securityContextRepository; private ServerWebExchangeMatcher switchUserMatcher = createMatcher("/login/impersonate"); private ServerWebExchangeMatcher exitUserMatcher = createMatcher("/logout/impersonate"); /** * Creates a filter for the user context switching * @param userDetailsService The <tt>UserDetailsService</tt> which will be used to * load information for the user that is being switched to. * @param successHandler Used to define custom behaviour on a successful switch or * exit user. * @param failureHandler Used to define custom behaviour when a switch fails. */ public SwitchUserWebFilter(ReactiveUserDetailsService userDetailsService, ServerAuthenticationSuccessHandler successHandler, @Nullable ServerAuthenticationFailureHandler failureHandler) { Assert.notNull(userDetailsService, "userDetailsService must be specified"); Assert.notNull(successHandler, "successHandler must be specified"); this.userDetailsService = userDetailsService; this.successHandler = successHandler; this.failureHandler = failureHandler; this.securityContextRepository = new WebSessionServerSecurityContextRepository(); this.userDetailsChecker = new AccountStatusUserDetailsChecker(); } /** * Creates a filter for the user context switching * @param userDetailsService The <tt>UserDetailsService</tt> which will be used to * load information for the user that is being switched to. * @param successTargetUrl Sets the URL to go to after a successful switch / exit user * request * @param failureTargetUrl The URL to which a user should be redirected if the switch * fails */ public SwitchUserWebFilter(ReactiveUserDetailsService userDetailsService, String successTargetUrl, @Nullable String failureTargetUrl) { Assert.notNull(userDetailsService, "userDetailsService must be specified"); Assert.notNull(successTargetUrl, "successTargetUrl must be specified"); this.userDetailsService = userDetailsService; this.successHandler = new RedirectServerAuthenticationSuccessHandler(successTargetUrl); this.failureHandler = (failureTargetUrl != null) ? new RedirectServerAuthenticationFailureHandler(failureTargetUrl) : null; this.securityContextRepository = new WebSessionServerSecurityContextRepository(); this.userDetailsChecker = new AccountStatusUserDetailsChecker(); } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { final WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain); return switchUser(webFilterExchange).switchIfEmpty(Mono.defer(() -> exitSwitchUser(webFilterExchange))) .switchIfEmpty(Mono.defer(() -> { this.logger.trace( LogMessage.format("Did not attempt to switch user since request did not match [%s] or [%s]", this.switchUserMatcher, this.exitUserMatcher)); return chain.filter(exchange).then(Mono.empty()); })).flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange)) .onErrorResume(SwitchUserAuthenticationException.class, (exception) -> Mono.empty()); } /** * Attempt to switch to another user. * @param webFilterExchange The web filter exchange * @return The new <code>Authentication</code> object if successfully switched to * another user, <code>Mono.empty()</code> otherwise. * @throws AuthenticationCredentialsNotFoundException If the target user can not be * found by username */ protected Mono<Authentication> switchUser(WebFilterExchange webFilterExchange) { return this.switchUserMatcher.matches(webFilterExchange.getExchange()) .filter(ServerWebExchangeMatcher.MatchResult::isMatch) .flatMap((matchResult) -> ReactiveSecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication).flatMap((currentAuthentication) -> { String username = getUsername(webFilterExchange.getExchange()); return attemptSwitchUser(currentAuthentication, username); }).onErrorResume(AuthenticationException.class, (ex) -> onAuthenticationFailure(ex, webFilterExchange) .then(Mono.error(new SwitchUserAuthenticationException(ex)))); } /** * Attempt to exit from an already switched user. * @param webFilterExchange The web filter exchange * @return The original <code>Authentication</code> object. * @throws AuthenticationCredentialsNotFoundException If there is no * <code>Authentication</code> associated with this request or the user is not * switched. */ protected Mono<Authentication> exitSwitchUser(WebFilterExchange webFilterExchange) { return this.exitUserMatcher.matches(webFilterExchange.getExchange()) .filter(ServerWebExchangeMatcher.MatchResult::isMatch) .flatMap((matchResult) -> ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .switchIfEmpty(Mono.error(this::noCurrentUserException))) .map(this::attemptExitUser); } /** * Returns the name of the target user. * @param exchange The server web exchange * @return the name of the target user. */ protected String getUsername(ServerWebExchange exchange) { return exchange.getRequest().getQueryParams().getFirst(SPRING_SECURITY_SWITCH_USERNAME_KEY); } @NonNull private Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); this.logger.debug(LogMessage.format("Attempting to switch to user [%s]", userName)); return this.userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(this.userDetailsChecker::check) .map((userDetails) -> createSwitchUserToken(userDetails, currentAuthentication)); } @NonNull private Authentication attemptExitUser(Authentication currentAuthentication) { Optional<Authentication> sourceAuthentication = extractSourceAuthentication(currentAuthentication); if (!sourceAuthentication.isPresent()) { this.logger.debug("Failed to find original user"); throw noOriginalAuthenticationException(); } return sourceAuthentication.get(); } private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { ServerWebExchange exchange = webFilterExchange.getExchange(); SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return this.securityContextRepository.save(exchange, securityContext) .doOnSuccess((v) -> this.logger.debug(LogMessage.format("Switched user to %s", authentication))) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); } private Mono<Void> onAuthenticationFailure(AuthenticationException exception, WebFilterExchange webFilterExchange) { return Mono.justOrEmpty(this.failureHandler).switchIfEmpty(Mono.defer(() -> { this.logger.debug("Failed to switch user", exception); return Mono.error(exception); })).flatMap((failureHandler) -> failureHandler.onAuthenticationFailure(webFilterExchange, exception)); } private Authentication createSwitchUserToken(UserDetails targetUser, Authentication currentAuthentication) { Optional<Authentication> sourceAuthentication = extractSourceAuthentication(currentAuthentication); if (sourceAuthentication.isPresent()) { // SEC-1763. Check first if we are already switched. this.logger.debug( LogMessage.format("Found original switch user granted authority [%s]", sourceAuthentication.get())); currentAuthentication = sourceAuthentication.get(); } GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, currentAuthentication); Collection<? extends GrantedAuthority> targetUserAuthorities = targetUser.getAuthorities(); List<GrantedAuthority> extendedTargetUserAuthorities = new ArrayList<>(targetUserAuthorities); extendedTargetUserAuthorities.add(switchAuthority); return UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(), extendedTargetUserAuthorities); } /** * Find the original <code>Authentication</code> object from the current user's * granted authorities. A successfully switched user should have a * <code>SwitchUserGrantedAuthority</code> that contains the original source user * <code>Authentication</code> object. * @param currentAuthentication The current <code>Authentication</code> object * @return The source user <code>Authentication</code> object or * <code>Optional.empty</code> otherwise. */ private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) { // iterate over granted authorities and find the 'switch user' authority for (GrantedAuthority authority : currentAuthentication.getAuthorities()) { if (authority instanceof SwitchUserGrantedAuthority switchAuthority) { return Optional.of(switchAuthority.getSource()); } } return Optional.empty(); } private static ServerWebExchangeMatcher createMatcher(String pattern) { return ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, pattern); } private AuthenticationCredentialsNotFoundException noCurrentUserException() { return new AuthenticationCredentialsNotFoundException("No current user associated with this request"); } private AuthenticationCredentialsNotFoundException noOriginalAuthenticationException() { return new AuthenticationCredentialsNotFoundException("Could not find original Authentication object"); } private AuthenticationCredentialsNotFoundException noTargetAuthenticationException() { return new AuthenticationCredentialsNotFoundException("No target user for the given username"); } /** * Sets the repository for persisting the SecurityContext. Default is * {@link WebSessionServerSecurityContextRepository} * @param securityContextRepository the repository to use */ public void setSecurityContextRepository(ServerSecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Set the URL to respond to exit user processing. This is a shortcut for * * {@link #setExitUserMatcher(ServerWebExchangeMatcher)} * @param exitUserUrl The exit user URL. */ public void setExitUserUrl(String exitUserUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(exitUserUrl), "exitUserUrl cannot be empty and must be a valid redirect URL"); this.exitUserMatcher = createMatcher(exitUserUrl); } /** * Set the matcher to respond to exit user processing. * @param exitUserMatcher The exit matcher to use */ public void setExitUserMatcher(ServerWebExchangeMatcher exitUserMatcher) { Assert.notNull(exitUserMatcher, "exitUserMatcher cannot be null"); this.exitUserMatcher = exitUserMatcher; } /** * Set the URL to respond to switch user processing. This is a shortcut for * {@link #setSwitchUserMatcher(ServerWebExchangeMatcher)} * @param switchUserUrl The switch user URL. */ public void setSwitchUserUrl(String switchUserUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(switchUserUrl), "switchUserUrl cannot be empty and must be a valid redirect URL"); this.switchUserMatcher = createMatcher(switchUserUrl); } /** * Set the matcher to respond to switch user processing. * @param switchUserMatcher The switch user matcher. */ public void setSwitchUserMatcher(ServerWebExchangeMatcher switchUserMatcher) { Assert.notNull(switchUserMatcher, "switchUserMatcher cannot be null"); this.switchUserMatcher = switchUserMatcher; } private static class SwitchUserAuthenticationException extends RuntimeException { SwitchUserAuthenticationException(AuthenticationException exception) { super(exception); } } }
17,267
46.701657
117
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverter.java
/* * Copyright 2002-2018 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.web.server.ServerWebExchange; /** * Converts a ServerWebExchange into a UsernamePasswordAuthenticationToken from the form * data HTTP parameters. * * @author Rob Winch * @since 5.1 */ @SuppressWarnings("deprecation") public class ServerFormLoginAuthenticationConverter extends org.springframework.security.web.server.ServerFormLoginAuthenticationConverter implements ServerAuthenticationConverter { @Override public Mono<Authentication> convert(ServerWebExchange exchange) { return apply(exchange); } }
1,330
30.690476
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandler.java
/* * Copyright 2002-2022 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Adapts a {@link ServerAuthenticationEntryPoint} into a * {@link ServerAuthenticationFailureHandler} * * @author Rob Winch * @since 5.0 */ public class ServerAuthenticationEntryPointFailureHandler implements ServerAuthenticationFailureHandler { private final ServerAuthenticationEntryPoint authenticationEntryPoint; private boolean rethrowAuthenticationServiceException = true; public ServerAuthenticationEntryPointFailureHandler(ServerAuthenticationEntryPoint authenticationEntryPoint) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; } @Override public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) { if (!this.rethrowAuthenticationServiceException) { return this.authenticationEntryPoint.commence(webFilterExchange.getExchange(), exception); } if (!AuthenticationServiceException.class.isAssignableFrom(exception.getClass())) { return this.authenticationEntryPoint.commence(webFilterExchange.getExchange(), exception); } return Mono.error(exception); } /** * Set whether to rethrow {@link AuthenticationServiceException}s (defaults to true) * @param rethrowAuthenticationServiceException whether to rethrow * {@link AuthenticationServiceException}s * @since 5.8 */ public void setRethrowAuthenticationServiceException(boolean rethrowAuthenticationServiceException) { this.rethrowAuthenticationServiceException = rethrowAuthenticationServiceException; } }
2,634
38.328358
116
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/ServerHttpBasicAuthenticationConverter.java
/* * Copyright 2002-2018 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.web.server.ServerWebExchange; /** * Converts from a {@link ServerWebExchange} to an {@link Authentication} that can be * authenticated. * * @author Rob Winch * @since 5.1 */ @SuppressWarnings("deprecation") public class ServerHttpBasicAuthenticationConverter extends org.springframework.security.web.server.ServerHttpBasicAuthenticationConverter implements ServerAuthenticationConverter { @Override public Mono<Authentication> convert(ServerWebExchange exchange) { return apply(exchange); } }
1,320
30.452381
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationWebFilter.java
/* * 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.server.authentication; import java.util.function.Function; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * A {@link WebFilter} that performs authentication of a particular request. An outline of * the logic: * * <ul> * <li>A request comes in and if it does not match * {@link #setRequiresAuthenticationMatcher(ServerWebExchangeMatcher)}, then this filter * does nothing and the {@link WebFilterChain} is continued. If it does match then...</li> * <li>An attempt to convert the {@link ServerWebExchange} into an {@link Authentication} * is made. If the result is empty, then the filter does nothing more and the * {@link WebFilterChain} is continued. If it does create an {@link Authentication}... * </li> * <li>The {@link ReactiveAuthenticationManager} specified in * {@link #AuthenticationWebFilter(ReactiveAuthenticationManager)} is used to perform * authentication.</li> * <li>The {@link ReactiveAuthenticationManagerResolver} specified in * {@link #AuthenticationWebFilter(ReactiveAuthenticationManagerResolver)} is used to * resolve the appropriate authentication manager from context to perform authentication. * </li> * <li>If authentication is successful, {@link ServerAuthenticationSuccessHandler} is * invoked and the authentication is set on {@link ReactiveSecurityContextHolder}, else * {@link ServerAuthenticationFailureHandler} is invoked</li> * </ul> * * @author Rob Winch * @author Rafiullah Hamedy * @author Mathieu Ouellet * @since 5.0 */ public class AuthenticationWebFilter implements WebFilter { private static final Log logger = LogFactory.getLog(AuthenticationWebFilter.class); private final ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver; private ServerAuthenticationSuccessHandler authenticationSuccessHandler = new WebFilterChainServerAuthenticationSuccessHandler(); private ServerAuthenticationConverter authenticationConverter = new ServerHttpBasicAuthenticationConverter(); private ServerAuthenticationFailureHandler authenticationFailureHandler = new ServerAuthenticationEntryPointFailureHandler( new HttpBasicServerAuthenticationEntryPoint()); private ServerSecurityContextRepository securityContextRepository = NoOpServerSecurityContextRepository .getInstance(); private ServerWebExchangeMatcher requiresAuthenticationMatcher = ServerWebExchangeMatchers.anyExchange(); /** * Creates an instance * @param authenticationManager the authentication manager to use */ public AuthenticationWebFilter(ReactiveAuthenticationManager authenticationManager) { Assert.notNull(authenticationManager, "authenticationManager cannot be null"); this.authenticationManagerResolver = (request) -> Mono.just(authenticationManager); } /** * Creates an instance * @param authenticationManagerResolver the authentication manager resolver to use * @since 5.3 */ public AuthenticationWebFilter( ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver) { Assert.notNull(authenticationManagerResolver, "authenticationResolverManager cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.requiresAuthenticationMatcher.matches(exchange).filter((matchResult) -> matchResult.isMatch()) .flatMap((matchResult) -> this.authenticationConverter.convert(exchange)) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .flatMap((token) -> authenticate(exchange, chain, token)) .onErrorResume(AuthenticationException.class, (ex) -> this.authenticationFailureHandler .onAuthenticationFailure(new WebFilterExchange(exchange, chain), ex)); } private Mono<Void> authenticate(ServerWebExchange exchange, WebFilterChain chain, Authentication token) { return this.authenticationManagerResolver.resolve(exchange) .flatMap((authenticationManager) -> authenticationManager.authenticate(token)) .switchIfEmpty(Mono.defer( () -> Mono.error(new IllegalStateException("No provider found for " + token.getClass())))) .flatMap((authentication) -> onAuthenticationSuccess(authentication, new WebFilterExchange(exchange, chain))) .doOnError(AuthenticationException.class, (ex) -> logger.debug(LogMessage.format("Authentication failed: %s", ex.getMessage()))); } protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { ServerWebExchange exchange = webFilterExchange.getExchange(); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); return this.securityContextRepository.save(exchange, securityContext) .then(this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); } /** * Sets the repository for persisting the SecurityContext. Default is * {@link NoOpServerSecurityContextRepository} * @param securityContextRepository the repository to use */ public void setSecurityContextRepository(ServerSecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the authentication success handler. Default is * {@link WebFilterChainServerAuthenticationSuccessHandler} * @param authenticationSuccessHandler the success handler to use */ public void setAuthenticationSuccessHandler(ServerAuthenticationSuccessHandler authenticationSuccessHandler) { Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null"); this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets the strategy used for converting from a {@link ServerWebExchange} to an * {@link Authentication} used for authenticating with the provided * {@link ReactiveAuthenticationManager}. If the result is empty, then it signals that * no authentication attempt should be made. The default converter is * {@link ServerHttpBasicAuthenticationConverter} * @param authenticationConverter the converter to use * @deprecated As of 5.1 in favor of * {@link #setServerAuthenticationConverter(ServerAuthenticationConverter)} * @see #setServerAuthenticationConverter(ServerAuthenticationConverter) */ @Deprecated public void setAuthenticationConverter(Function<ServerWebExchange, Mono<Authentication>> authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); setServerAuthenticationConverter(authenticationConverter::apply); } /** * Sets the strategy used for converting from a {@link ServerWebExchange} to an * {@link Authentication} used for authenticating with the provided * {@link ReactiveAuthenticationManager}. If the result is empty, then it signals that * no authentication attempt should be made. The default converter is * {@link ServerHttpBasicAuthenticationConverter} * @param authenticationConverter the converter to use * @since 5.1 */ public void setServerAuthenticationConverter(ServerAuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } /** * Sets the failure handler used when authentication fails. The default is to prompt * for basic authentication. * @param authenticationFailureHandler the handler to use. Cannot be null. */ public void setAuthenticationFailureHandler(ServerAuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler; } /** * Sets the matcher used to determine when creating an {@link Authentication} from * {@link #setServerAuthenticationConverter(ServerAuthenticationConverter)} to be * authentication. If the converter returns an empty result, then no authentication is * attempted. The default is any request * @param requiresAuthenticationMatcher the matcher to use. Cannot be null. */ public void setRequiresAuthenticationMatcher(ServerWebExchangeMatcher requiresAuthenticationMatcher) { Assert.notNull(requiresAuthenticationMatcher, "requiresAuthenticationMatcher cannot be null"); this.requiresAuthenticationMatcher = requiresAuthenticationMatcher; } }
10,487
48.239437
130
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/HttpBasicServerAuthenticationEntryPoint.java
/* * Copyright 2002-2017 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Prompts a user for HTTP Basic authentication. * * @author Rob Winch * @since 5.0 */ public class HttpBasicServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint { private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private static final String DEFAULT_REALM = "Realm"; private static String WWW_AUTHENTICATE_FORMAT = "Basic realm=\"%s\""; private String headerValue = createHeaderValue(DEFAULT_REALM); @Override public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) { return Mono.fromRunnable(() -> { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().set(WWW_AUTHENTICATE, this.headerValue); }); } /** * Sets the realm to be used * @param realm the realm. Default is "Realm" */ public void setRealm(String realm) { this.headerValue = createHeaderValue(realm); } private static String createHeaderValue(String realm) { Assert.notNull(realm, "realm cannot be null"); return String.format(WWW_AUTHENTICATE_FORMAT, realm); } }
2,195
31.776119
96
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/HttpStatusServerEntryPoint.java
/* * Copyright 2002-2018 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.server.authentication; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * A {@link ServerAuthenticationEntryPoint} that sends a generic {@link HttpStatus} as a * response. Useful for JavaScript clients which cannot use Basic authentication since the * browser intercepts the response. * * @author Eric Deandrea * @since 5.1 */ public class HttpStatusServerEntryPoint implements ServerAuthenticationEntryPoint { private final HttpStatus httpStatus; public HttpStatusServerEntryPoint(HttpStatus httpStatus) { Assert.notNull(httpStatus, "httpStatus cannot be null"); this.httpStatus = httpStatus; } @Override public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException authException) { return Mono.fromRunnable(() -> exchange.getResponse().setStatusCode(this.httpStatus)); } }
1,760
34.22
96
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/RedirectServerLogoutSuccessHandler.java
/* * Copyright 2002-2017 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.server.authentication.logout; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Performs a redirect on log out success. * * @author Rob Winch * @since 5.0 */ public class RedirectServerLogoutSuccessHandler implements ServerLogoutSuccessHandler { public static final String DEFAULT_LOGOUT_SUCCESS_URL = "/login?logout"; private URI logoutSuccessUrl = URI.create(DEFAULT_LOGOUT_SUCCESS_URL); private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); @Override public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) { return this.redirectStrategy.sendRedirect(exchange.getExchange(), this.logoutSuccessUrl); } /** * The URL to redirect to after successfully logging out. * @param logoutSuccessUrl the url to redirect to. Default is "/login?logout". */ public void setLogoutSuccessUrl(URI logoutSuccessUrl) { Assert.notNull(logoutSuccessUrl, "logoutSuccessUrl cannot be null"); this.logoutSuccessUrl = logoutSuccessUrl; } }
2,012
33.706897
95
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/LogoutWebFilter.java
/* * 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.server.authentication.logout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * If the request matches, logs an authenticated user out by delegating to a * {@link ServerLogoutHandler}. * * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 */ public class LogoutWebFilter implements WebFilter { private static final Log logger = LogFactory.getLog(LogoutWebFilter.class); private AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken("key", "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); private ServerLogoutHandler logoutHandler = new SecurityContextServerLogoutHandler(); private ServerLogoutSuccessHandler logoutSuccessHandler = new RedirectServerLogoutSuccessHandler(); private ServerWebExchangeMatcher requiresLogout = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/logout"); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.requiresLogout.matches(exchange).filter((result) -> result.isMatch()) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())).map((result) -> exchange) .flatMap(this::flatMapAuthentication).flatMap((authentication) -> { WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain); return logout(webFilterExchange, authentication); }); } private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) { return exchange.getPrincipal().cast(Authentication.class).defaultIfEmpty(this.anonymousAuthenticationToken); } private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) { logger.debug(LogMessage.format("Logging out user '%s' and transferring to logout destination", authentication)); return this.logoutHandler.logout(webFilterExchange, authentication) .then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.clearContext()); } /** * Sets the {@link ServerLogoutSuccessHandler}. The default is * {@link RedirectServerLogoutSuccessHandler}. * @param logoutSuccessHandler the handler to use */ public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) { Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null"); this.logoutSuccessHandler = logoutSuccessHandler; } /** * Sets the {@link ServerLogoutHandler}. The default is * {@link SecurityContextServerLogoutHandler}. * @param logoutHandler The handler to use */ public void setLogoutHandler(ServerLogoutHandler logoutHandler) { Assert.notNull(logoutHandler, "logoutHandler must not be null"); this.logoutHandler = logoutHandler; } public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) { Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null"); this.requiresLogout = requiresLogoutMatcher; } }
4,515
41.603774
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/WebSessionServerLogoutHandler.java
/* * Copyright 2002-2021 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.WebSession; /** * A {@link ServerLogoutHandler} which invalidates the active {@link WebSession}. * * @author Bogdan Ilchyshyn * @since 5.6 */ public class WebSessionServerLogoutHandler implements ServerLogoutHandler { @Override public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) { return exchange.getExchange().getSession().flatMap(WebSession::invalidate); } }
1,300
32.358974
86
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/ServerLogoutSuccessHandler.java
/* * Copyright 2002-2017 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; /** * Strategy for when log out was successfully performed (typically after * {@link ServerLogoutHandler} is invoked). * * @author Rob Winch * @since 5.0 * @see ServerLogoutHandler */ public interface ServerLogoutSuccessHandler { /** * Invoked after log out was successful * @param exchange the exchange * @param authentication the {@link Authentication} * @return a completion notification (success or error) */ Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication); }
1,379
31.093023
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandler.java
/* * Copyright 2002-2018 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.server.authentication.logout; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Delegates to a collection of {@link ServerLogoutHandler} implementations. * * @author Eric Deandrea * @since 5.1 */ public class DelegatingServerLogoutHandler implements ServerLogoutHandler { private final List<ServerLogoutHandler> delegates = new ArrayList<>(); public DelegatingServerLogoutHandler(ServerLogoutHandler... delegates) { Assert.notEmpty(delegates, "delegates cannot be null or empty"); this.delegates.addAll(Arrays.asList(delegates)); } public DelegatingServerLogoutHandler(Collection<ServerLogoutHandler> delegates) { Assert.notEmpty(delegates, "delegates cannot be null or empty"); this.delegates.addAll(delegates); } @Override public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) { return Flux.fromIterable(this.delegates).concatMap((delegate) -> delegate.logout(exchange, authentication)) .then(); } }
1,928
32.258621
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/SecurityContextServerLogoutHandler.java
/* * Copyright 2002-2017 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; import org.springframework.util.Assert; /** * A {@link ServerLogoutHandler} which removes the SecurityContext using the provided * {@link ServerSecurityContextRepository} * * @author Rob Winch * @since 5.0 */ public class SecurityContextServerLogoutHandler implements ServerLogoutHandler { private ServerSecurityContextRepository securityContextRepository = new WebSessionServerSecurityContextRepository(); @Override public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) { return this.securityContextRepository.save(exchange.getExchange(), null); } /** * Sets the {@link ServerSecurityContextRepository} that should be used for logging * out. Default is {@link WebSessionServerSecurityContextRepository} * @param securityContextRepository the {@link ServerSecurityContextRepository} to * use. */ public void setSecurityContextRepository(ServerSecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } }
2,154
38.181818
117
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/HttpStatusReturningServerLogoutSuccessHandler.java
/* * Copyright 2002-2018 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.util.Assert; /** * Implementation of the {@link ServerLogoutSuccessHandler}. By default returns an HTTP * status code of {@code 200}. This is useful in REST-type scenarios where a redirect upon * a successful logout is not desired. * * @author Eric Deandrea * @since 5.1 */ public class HttpStatusReturningServerLogoutSuccessHandler implements ServerLogoutSuccessHandler { private final HttpStatus httpStatusToReturn; /** * Initialize the {@code HttpStatusReturningServerLogoutSuccessHandler} with a * user-defined {@link HttpStatus}. * @param httpStatusToReturn Must not be {@code null}. */ public HttpStatusReturningServerLogoutSuccessHandler(HttpStatus httpStatusToReturn) { Assert.notNull(httpStatusToReturn, "The provided HttpStatus must not be null."); this.httpStatusToReturn = httpStatusToReturn; } /** * Initialize the {@code HttpStatusReturningServerLogoutSuccessHandler} with the * default {@link HttpStatus#OK}. */ public HttpStatusReturningServerLogoutSuccessHandler() { this.httpStatusToReturn = HttpStatus.OK; } /** * Implementation of * {@link ServerLogoutSuccessHandler#onLogoutSuccess(WebFilterExchange, Authentication)}. * Sets the status on the {@link WebFilterExchange}. * @param exchange The exchange * @param authentication The {@link Authentication} * @return A completion notification (success or error) */ @Override public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) { return Mono.fromRunnable(() -> exchange.getExchange().getResponse().setStatusCode(this.httpStatusToReturn)); } }
2,536
35.242857
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandler.java
/* * Copyright 2002-2019 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.header.ServerHttpHeadersWriter; import org.springframework.util.Assert; /** * <p> * A {@link ServerLogoutHandler} implementation which writes HTTP headers during logout. * </p> * * @author MD Sayem Ahmed * @since 5.2 */ public final class HeaderWriterServerLogoutHandler implements ServerLogoutHandler { private final ServerHttpHeadersWriter headersWriter; /** * <p> * Constructs a new instance using the {@link ServerHttpHeadersWriter} implementation. * </p> * @param headersWriter a {@link ServerHttpHeadersWriter} implementation * @throws IllegalArgumentException if the argument is null */ public HeaderWriterServerLogoutHandler(ServerHttpHeadersWriter headersWriter) { Assert.notNull(headersWriter, "headersWriter cannot be null"); this.headersWriter = headersWriter; } @Override public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) { return this.headersWriter.writeHttpHeaders(exchange.getExchange()); } }
1,882
32.625
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authentication/logout/ServerLogoutHandler.java
/* * Copyright 2002-2017 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.server.authentication.logout; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; /** * Handles log out * * @author Rob Winch * @since 5.0 * @see ServerLogoutSuccessHandler */ public interface ServerLogoutHandler { /** * Invoked when log out is requested * @param exchange the exchange * @param authentication the {@link Authentication} * @return a completion notification (success or error) */ Mono<Void> logout(WebFilterExchange exchange, Authentication authentication); }
1,269
29.238095
78
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/AuthorizationWebFilter.java
/* * 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.server.authorization; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 */ public class AuthorizationWebFilter implements WebFilter { private static final Log logger = LogFactory.getLog(AuthorizationWebFilter.class); private ReactiveAuthorizationManager<? super ServerWebExchange> authorizationManager; public AuthorizationWebFilter(ReactiveAuthorizationManager<? super ServerWebExchange> authorizationManager) { this.authorizationManager = authorizationManager; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return ReactiveSecurityContextHolder.getContext().filter((c) -> c.getAuthentication() != null) .map(SecurityContext::getAuthentication) .as((authentication) -> this.authorizationManager.verify(authentication, exchange)) .doOnSuccess((it) -> logger.debug("Authorization successful")) .doOnError(AccessDeniedException.class, (ex) -> logger.debug(LogMessage.format("Authorization failed: %s", ex.getMessage()))) .switchIfEmpty(chain.filter(exchange)); } }
2,352
38.881356
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/ServerAccessDeniedHandler.java
/* * Copyright 2002-2017 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.server.authorization; import reactor.core.publisher.Mono; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.server.ServerWebExchange; /** * @author Rob Winch * @since 5.0 */ public interface ServerAccessDeniedHandler { Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied); }
1,018
29.878788
77
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilter.java
/* * Copyright 2002-2022 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.server.authorization; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * @author Rob Winch * @author César Revert * @since 5.0 */ public class ExceptionTranslationWebFilter implements WebFilter { private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint(); private ServerAccessDeniedHandler accessDeniedHandler = new HttpStatusServerAccessDeniedHandler( HttpStatus.FORBIDDEN); private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange).onErrorResume(AccessDeniedException.class, (denied) -> exchange.getPrincipal() .filter((principal) -> (!(principal instanceof Authentication) || (principal instanceof Authentication && !(this.authenticationTrustResolver.isAnonymous((Authentication) principal))))) .switchIfEmpty(commenceAuthentication(exchange, new InsufficientAuthenticationException( "Full authentication is required to access this resource"))) .flatMap((principal) -> this.accessDeniedHandler.handle(exchange, denied)).then()); } /** * Sets the access denied handler. * @param accessDeniedHandler the access denied handler to use. Default is * HttpStatusAccessDeniedHandler with HttpStatus.FORBIDDEN */ public void setAccessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null"); this.accessDeniedHandler = accessDeniedHandler; } /** * Sets the authentication entry point used when authentication is required * @param authenticationEntryPoint the authentication entry point to use. Default is * {@link HttpBasicServerAuthenticationEntryPoint} */ public void setAuthenticationEntryPoint(ServerAuthenticationEntryPoint authenticationEntryPoint) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; } /** * Sets the authentication trust resolver. * @param authenticationTrustResolver the authentication trust resolver to use. * Default is {@link AuthenticationTrustResolverImpl} * * @since 5.5 */ public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver) { Assert.notNull(authenticationTrustResolver, "authenticationTrustResolver must not be null"); this.authenticationTrustResolver = authenticationTrustResolver; } private <T> Mono<T> commenceAuthentication(ServerWebExchange exchange, AuthenticationException denied) { return this.authenticationEntryPoint .commence(exchange, new AuthenticationCredentialsNotFoundException("Not Authenticated", denied)) .then(Mono.empty()); } }
4,451
43.52
113
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/HttpStatusServerAccessDeniedHandler.java
/* * Copyright 2002-2017 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.server.authorization; import java.nio.charset.Charset; import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * Sets the provided HTTP Status when access is denied. * * @author Rob Winch * @since 5.0 */ public class HttpStatusServerAccessDeniedHandler implements ServerAccessDeniedHandler { private final HttpStatus httpStatus; /** * Creates an instance with the provided status * @param httpStatus the status to use */ public HttpStatusServerAccessDeniedHandler(HttpStatus httpStatus) { Assert.notNull(httpStatus, "httpStatus cannot be null"); this.httpStatus = httpStatus; } @Override public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException ex) { return Mono.defer(() -> Mono.just(exchange.getResponse())).flatMap((response) -> { response.setStatusCode(this.httpStatus); response.getHeaders().setContentType(MediaType.TEXT_PLAIN); DataBufferFactory dataBufferFactory = response.bufferFactory(); DataBuffer buffer = dataBufferFactory.wrap(ex.getMessage().getBytes(Charset.defaultCharset())); return response.writeWith(Mono.just(buffer)).doOnError((error) -> DataBufferUtils.release(buffer)); }); } }
2,242
34.603175
102
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandler.java
/* * Copyright 2002-2018 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.server.authorization; import java.util.Arrays; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * A {@link ServerAccessDeniedHandler} which delegates to multiple * {@link ServerAccessDeniedHandler}s based on a {@link ServerWebExchangeMatcher} * * @author Josh Cummings * @since 5.1 */ public class ServerWebExchangeDelegatingServerAccessDeniedHandler implements ServerAccessDeniedHandler { private final List<DelegateEntry> handlers; private ServerAccessDeniedHandler defaultHandler = (exchange, ex) -> { exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); return exchange.getResponse().setComplete(); }; /** * Creates a new instance * @param handlers a list of {@link ServerWebExchangeMatcher}/ * {@link ServerAccessDeniedHandler} pairs that should be used. Each is considered in * the order they are specified and only the first {@link ServerAccessDeniedHandler} * is used. If none match, then the default {@link ServerAccessDeniedHandler} is used. */ public ServerWebExchangeDelegatingServerAccessDeniedHandler(DelegateEntry... handlers) { this(Arrays.asList(handlers)); } /** * Creates a new instance * @param handlers a list of {@link ServerWebExchangeMatcher}/ * {@link ServerAccessDeniedHandler} pairs that should be used. Each is considered in * the order they are specified and only the first {@link ServerAccessDeniedHandler} * is used. If none match, then the default {@link ServerAccessDeniedHandler} is used. */ public ServerWebExchangeDelegatingServerAccessDeniedHandler(List<DelegateEntry> handlers) { Assert.notEmpty(handlers, "handlers cannot be null"); this.handlers = handlers; } @Override public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) { return Flux.fromIterable(this.handlers).filterWhen((entry) -> isMatch(exchange, entry)).next() .map(DelegateEntry::getAccessDeniedHandler).defaultIfEmpty(this.defaultHandler) .flatMap((handler) -> handler.handle(exchange, denied)); } /** * Use this {@link ServerAccessDeniedHandler} when no {@link ServerWebExchangeMatcher} * matches. * @param accessDeniedHandler - the default {@link ServerAccessDeniedHandler} to use */ public void setDefaultAccessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null"); this.defaultHandler = accessDeniedHandler; } private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) { ServerWebExchangeMatcher matcher = entry.getMatcher(); return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch); } public static class DelegateEntry { private final ServerWebExchangeMatcher matcher; private final ServerAccessDeniedHandler accessDeniedHandler; public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAccessDeniedHandler accessDeniedHandler) { this.matcher = matcher; this.accessDeniedHandler = accessDeniedHandler; } public ServerWebExchangeMatcher getMatcher() { return this.matcher; } public ServerAccessDeniedHandler getAccessDeniedHandler() { return this.accessDeniedHandler; } } }
4,189
35.754386
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManager.java
/* * 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.server.authorization; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.log.LogMessage; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry; import org.springframework.web.server.ServerWebExchange; /** * @author Rob Winch * @author Mathieu Ouellet * @since 5.0 */ public final class DelegatingReactiveAuthorizationManager implements ReactiveAuthorizationManager<ServerWebExchange> { private static final Log logger = LogFactory.getLog(DelegatingReactiveAuthorizationManager.class); private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings; private DelegatingReactiveAuthorizationManager( List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings) { this.mappings = mappings; } @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, ServerWebExchange exchange) { return Flux.fromIterable(this.mappings).concatMap((mapping) -> mapping.getMatcher().matches(exchange) .filter(MatchResult::isMatch).map(MatchResult::getVariables).flatMap((variables) -> { logger.debug(LogMessage.of(() -> "Checking authorization on '" + exchange.getRequest().getPath().pathWithinApplication() + "' using " + mapping.getEntry())); return mapping.getEntry().check(authentication, new AuthorizationContext(exchange, variables)); })).next().defaultIfEmpty(new AuthorizationDecision(false)); } public static DelegatingReactiveAuthorizationManager.Builder builder() { return new DelegatingReactiveAuthorizationManager.Builder(); } public static final class Builder { private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings = new ArrayList<>(); private Builder() { } public DelegatingReactiveAuthorizationManager.Builder add( ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>> entry) { this.mappings.add(entry); return this; } public DelegatingReactiveAuthorizationManager build() { return new DelegatingReactiveAuthorizationManager(this.mappings); } } }
3,337
37.813953
133
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/AuthorizationContext.java
/* * Copyright 2002-2017 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.server.authorization; import java.util.Collections; import java.util.Map; import org.springframework.web.server.ServerWebExchange; /** * @author Rob Winch * @since 5.0 */ public class AuthorizationContext { private final ServerWebExchange exchange; private final Map<String, Object> variables; public AuthorizationContext(ServerWebExchange exchange) { this(exchange, Collections.emptyMap()); } public AuthorizationContext(ServerWebExchange exchange, Map<String, Object> variables) { this.exchange = exchange; this.variables = variables; } public ServerWebExchange getExchange() { return this.exchange; } public Map<String, Object> getVariables() { return Collections.unmodifiableMap(this.variables); } }
1,401
25.961538
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManager.java
/* * Copyright 2002-2021 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.server.authorization; import reactor.core.publisher.Mono; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.util.matcher.IpAddressServerWebExchangeMatcher; import org.springframework.util.Assert; /** * A {@link ReactiveAuthorizationManager}, that determines if the current request contains * the specified address or range of addresses * * @author Guirong Hu * @since 5.7 */ public final class IpAddressReactiveAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> { private final IpAddressServerWebExchangeMatcher ipAddressExchangeMatcher; IpAddressReactiveAuthorizationManager(String ipAddress) { this.ipAddressExchangeMatcher = new IpAddressServerWebExchangeMatcher(ipAddress); } @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext context) { return Mono.just(context.getExchange()).flatMap(this.ipAddressExchangeMatcher::matches) .map((matchResult) -> new AuthorizationDecision(matchResult.isMatch())); } /** * Creates an instance of {@link IpAddressReactiveAuthorizationManager} with the * provided IP address. * @param ipAddress the address or range of addresses from which the request must * @return the new instance */ public static IpAddressReactiveAuthorizationManager hasIpAddress(String ipAddress) { Assert.notNull(ipAddress, "This IP address is required; it must not be null"); return new IpAddressReactiveAuthorizationManager(ipAddress); } }
2,358
38.316667
120
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilter.java
/* * Copyright 2002-2019 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.server.transport; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.security.web.PortMapper; import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.util.UriComponentsBuilder; /** * Redirects any non-HTTPS request to its HTTPS equivalent. * * Can be configured to use a {@link ServerWebExchangeMatcher} to narrow which requests * get redirected. * * Can also be configured for custom ports using {@link PortMapper}. * * @author Josh Cummings * @since 5.1 */ public final class HttpsRedirectWebFilter implements WebFilter { private PortMapper portMapper = new PortMapperImpl(); private ServerWebExchangeMatcher requiresHttpsRedirectMatcher = ServerWebExchangeMatchers.anyExchange(); private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return Mono.just(exchange).filter(this::isInsecure).flatMap(this.requiresHttpsRedirectMatcher::matches) .filter((matchResult) -> matchResult.isMatch()).switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .map((matchResult) -> createRedirectUri(exchange)) .flatMap((uri) -> this.redirectStrategy.sendRedirect(exchange, uri)); } /** * Use this {@link PortMapper} for mapping custom ports * @param portMapper the {@link PortMapper} to use */ public void setPortMapper(PortMapper portMapper) { Assert.notNull(portMapper, "portMapper cannot be null"); this.portMapper = portMapper; } /** * Use this {@link ServerWebExchangeMatcher} to narrow which requests are redirected * to HTTPS. * * The filter already first checks for HTTPS in the uri scheme, so it is not necessary * to include that check in this matcher. * @param requiresHttpsRedirectMatcher the {@link ServerWebExchangeMatcher} to use */ public void setRequiresHttpsRedirectMatcher(ServerWebExchangeMatcher requiresHttpsRedirectMatcher) { Assert.notNull(requiresHttpsRedirectMatcher, "requiresHttpsRedirectMatcher cannot be null"); this.requiresHttpsRedirectMatcher = requiresHttpsRedirectMatcher; } private boolean isInsecure(ServerWebExchange exchange) { return !"https".equals(exchange.getRequest().getURI().getScheme()); } private URI createRedirectUri(ServerWebExchange exchange) { int port = exchange.getRequest().getURI().getPort(); UriComponentsBuilder builder = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()); if (port > 0) { Integer httpsPort = this.portMapper.lookupHttpsPort(port); Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port"); builder.port(httpsPort); } return builder.scheme("https").build().toUri(); } }
3,970
38.71
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/http/SecurityHeaders.java
/* * Copyright 2002-2018 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.http; import java.util.function.Consumer; import org.springframework.http.HttpHeaders; import org.springframework.util.Assert; /** * Utilities for interacting with {@link HttpHeaders} * * @author Rob Winch * @since 5.1 */ public final class SecurityHeaders { private SecurityHeaders() { } /** * Sets the provided value as a Bearer token in a header with the name of * {@link HttpHeaders#AUTHORIZATION} * @param bearerTokenValue the bear token value * @return a {@link Consumer} that sets the header. */ public static Consumer<HttpHeaders> bearerToken(String bearerTokenValue) { Assert.hasText(bearerTokenValue, "bearerTokenValue cannot be null"); return (headers) -> headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + bearerTokenValue); } }
1,435
29.553191
91
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersAnnotatedTests.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import java.util.concurrent.ForkJoinPool; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(SpringExtension.class) @SecurityTestExecutionListeners public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test @WithMockUser public void withMockUserWhenOnMethodThenSuccess() { this.client.get().exchange().expectStatus().isOk(); Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test @WithMockUser public void withMockUserWhenGlobalMockPrincipalThenOverridesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client = WebTestClient.bindToController(this.controller) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()) .apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test @WithMockUser public void withMockUserWhenMutateWithMockPrincipalThenOverridesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test @WithMockUser public void withMockUserWhenMutateWithMockPrincipalAndNoMutateThenOverridesAnnotationAndUsesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); this.client.get().exchange().expectStatus().isOk(); assertPrincipalCreatedFromUserDetails(this.controller.removePrincipal(), this.userBuilder.build()); } @Test @WithMockUser public void withMockUserWhenOnMethodAndRequestIsExecutedOnDifferentThreadThenSuccess() { Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); ForkJoinPool.commonPool().submit(() -> this.client.get().exchange().expectStatus().isOk()).join(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test @WithMockUser public void withMockUserAndWithCallOnSeparateThreadWhenMutateWithMockPrincipalAndNoMutateThenOverridesAnnotationAndUsesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); ForkJoinPool.commonPool() .submit(() -> this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)) .get().exchange().expectStatus().isOk()) .join(); this.controller.assertPrincipalIsEqualTo(authentication); ForkJoinPool.commonPool().submit(() -> this.client.get().exchange().expectStatus().isOk()).join(); assertPrincipalCreatedFromUserDetails(this.controller.removePrincipal(), this.userBuilder.build()); } }
5,162
43.895652
134
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersTests.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import java.security.Principal; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.security.web.server.csrf.CsrfWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) .webFilter(new CsrfWebFilter(), new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockAuthenticationWhenLocalThenSuccess() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test public void mockAuthenticationWhenGlobalThenSuccess() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client = WebTestClient.bindToController(this.controller) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()) .apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test public void mockUserWhenDefaultsThenSuccess() { this.client.mutateWith(SecurityMockServerConfigurers.mockUser()).get().exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build()); } @Test public void mockUserWhenGlobalThenSuccess() { this.client = WebTestClient.bindToController(this.controller) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.mockUser()) .configureClient().defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build()); } @Test public void mockUserStringWhenLocalThenSuccess() { this.client.mutateWith(SecurityMockServerConfigurers.mockUser(this.userBuilder.build().getUsername())).get() .exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build()); } @Test public void mockUserStringWhenCustomThenSuccess() { this.userBuilder = User.withUsername("admin").password("secret").roles("USER", "ADMIN"); this.client .mutateWith(SecurityMockServerConfigurers.mockUser("admin").password("secret").roles("USER", "ADMIN")) .get().exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build()); } @Test public void mockUserUserDetailsLocalThenSuccess() { UserDetails userDetails = this.userBuilder.build(); this.client.mutateWith(SecurityMockServerConfigurers.mockUser(userDetails)).get().exchange().expectStatus() .isOk(); Principal actual = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build()); } @Test public void csrfWhenMutateWithThenDisablesCsrf() { this.client.post().exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN).expectBody() .consumeWith((b) -> assertThat(new String(b.getResponseBody())).contains("CSRF")); this.client.mutateWith(SecurityMockServerConfigurers.csrf()).post().exchange().expectStatus().isOk(); } @Test public void csrfWhenGlobalThenDisablesCsrf() { this.client = WebTestClient.bindToController(this.controller).webFilter(new CsrfWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.csrf()) .configureClient().build(); this.client.get().exchange().expectStatus().isOk(); } }
5,625
42.612403
110
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOidcLoginTests.java
/* * 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.test.web.reactive.server; import java.util.Collection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockServerConfigurersTests { private OAuth2LoginController controller = new OAuth2LoginController(); @Mock private ReactiveClientRegistrationRepository clientRegistrationRepository; @Mock private ServerOAuth2AuthorizedClientRepository authorizedClientRepository; private WebTestClient client; @BeforeEach public void setup() { this.client = WebTestClient.bindToController(this.controller) .argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository))) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @Test public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication() { this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/token").exchange() .expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token).isNotNull(); assertThat(token.getAuthorizedClientRegistrationId()).isEqualTo("test"); assertThat(token.getPrincipal()).isInstanceOf(OidcUser.class); assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "user"); assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities()) .contains(new SimpleGrantedAuthority("SCOPE_read")); assertThat(((OidcUser) token.getPrincipal()).getIdToken().getTokenValue()).isEqualTo("id-token"); } @Test public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() { this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/client").exchange() .expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("test"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("access-token"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oidcLoginWhenAuthoritiesSpecifiedThenGrantsAccess() { this.client .mutateWith(SecurityMockServerConfigurers.mockOidcLogin() .authorities(new SimpleGrantedAuthority("SCOPE_admin"))) .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities()) .contains(new SimpleGrantedAuthority("SCOPE_admin")); } @Test public void oidcLoginWhenIdTokenSpecifiedThenUserHasClaims() { this.client .mutateWith(SecurityMockServerConfigurers.mockOidcLogin() .idToken((i) -> i.issuer("https://idp.example.org"))) .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org"); } @Test public void oidcLoginWhenUserInfoSpecifiedThenUserHasClaims() throws Exception { this.client .mutateWith(SecurityMockServerConfigurers.mockOidcLogin().userInfoToken((u) -> u.email("email@email"))) .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("email", "email@email"); } @Test public void oidcUserWhenNameSpecifiedThenUserHasName() throws Exception { OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(), "custom-attribute"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get().uri("/token") .exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getName()).isEqualTo("test-subject"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get() .uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client.getPrincipalName()).isEqualTo("test-subject"); } // gh-7794 @Test public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception { OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), TestOidcIdTokens.idToken().build()); this.client.mutateWith( SecurityMockServerConfigurers.mockOidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser)).get() .uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject"); this.client.mutateWith( SecurityMockServerConfigurers.mockOidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar"))).get() .uri("/token").exchange().expectStatus().isOk(); token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar"); } @RestController static class OAuth2LoginController { volatile OAuth2AuthenticationToken token; volatile OAuth2AuthorizedClient authorizedClient; @GetMapping("/token") OAuth2AuthenticationToken token(OAuth2AuthenticationToken token) { this.token = token; return token; } @GetMapping("/client") String authorizedClient(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) { this.authorizedClient = authorizedClient; return authorizedClient.getPrincipalName(); } } }
8,269
44.690608
127
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java
/* * Copyright 2002-2023 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.test.web.reactive.server; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager; import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.OAuth2ClientMutator.TestOAuth2AuthorizedClientRepository; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.DispatcherHandler; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMockServerConfigurersTests { private OAuth2LoginController controller = new OAuth2LoginController(); @Mock private ReactiveClientRegistrationRepository clientRegistrationRepository; @Mock private ServerOAuth2AuthorizedClientRepository authorizedClientRepository; private ReactiveOAuth2AuthorizedClientManager authorizedClientManager; private WebTestClient client; @BeforeEach public void setup() { this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); this.client = WebTestClient.bindToController(this.controller) .argumentResolvers((c) -> c .addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(this.authorizedClientManager))) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @Test public void oauth2ClientWhenUsingDefaultsThenException() throws Exception { WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(new DispatcherHandler()); assertThatIllegalArgumentException() .isThrownBy(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder)) .withMessageContaining("ClientRegistration"); } @Test public void oauth2ClientWhenUsingRegistrationIdThenProducesAuthorizedClient() throws Exception { this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client") .exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("access-token"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oauth2ClientWhenClientRegistrationThenUses() throws Exception { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() .registrationId("registration-id").clientId("client-id").build(); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client().clientRegistration(clientRegistration)) .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("access-token"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception { this.client .mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id") .clientRegistration((c) -> c.clientId("client-id"))) .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id"); assertThat(client.getClientRegistration().getClientId()).isEqualTo("client-id"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("access-token"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oauth2ClientWhenPrincipalNameThenUses() throws Exception { this.client .mutateWith( SecurityMockServerConfigurers.mockOAuth2Client("registration-id").principalName("test-subject")) .get().uri("/client").exchange().expectStatus().isOk().expectBody(String.class) .isEqualTo("test-subject"); } @Test public void oauth2ClientWhenAccessTokenThenUses() throws Exception { OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes(); this.client .mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id").accessToken(accessToken)) .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("no-scopes"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception { this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client") .exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getClientId()).isEqualTo("test-client"); client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(), "sub", TestOAuth2AccessTokens.noScopes()); given(this.authorizedClientRepository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(ServerWebExchange.class))).willReturn(Mono.just(client)); this.client.get().uri("/client").exchange().expectStatus().isOk(); client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getClientId()).isEqualTo("client-id"); verify(this.authorizedClientRepository).loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(ServerWebExchange.class)); } // gh-13113 @Test public void oauth2ClientWhenUsedThenSetsClientToRepository() { this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")) .mutateWith((clientBuilder, httpBuilder, connector) -> httpBuilder .filters((filters) -> filters.add((exchange, chain) -> { ServerOAuth2AuthorizedClientRepository repository = (ServerOAuth2AuthorizedClientRepository) ReflectionTestUtils .getField(this.authorizedClientManager, "authorizedClientRepository"); assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class); return repository.loadAuthorizedClient("registration-id", null, exchange) .switchIfEmpty(Mono.error(new AssertionError("no authorized client found"))) .then(chain.filter(exchange)); }))) .get().uri("/client").exchange().expectStatus().isOk(); } @RestController static class OAuth2LoginController { volatile OAuth2AuthorizedClient authorizedClient; @GetMapping("/client") String authorizedClient( @RegisteredOAuth2AuthorizedClient("registration-id") OAuth2AuthorizedClient authorizedClient) { this.authorizedClient = authorizedClient; return authorizedClient.getPrincipalName(); } } }
9,971
48.123153
148
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2LoginTests.java
/* * 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.test.web.reactive.server; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockServerConfigurersTests { private OAuth2LoginController controller = new OAuth2LoginController(); @Mock private ReactiveClientRegistrationRepository clientRegistrationRepository; @Mock private ServerOAuth2AuthorizedClientRepository authorizedClientRepository; private WebTestClient client; @BeforeEach public void setup() { this.client = WebTestClient.bindToController(this.controller) .argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository))) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthentication() { this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/token").exchange() .expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token).isNotNull(); assertThat(token.getAuthorizedClientRegistrationId()).isEqualTo("test"); assertThat(token.getPrincipal()).isInstanceOf(OAuth2User.class); assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "user"); assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities()) .contains(new SimpleGrantedAuthority("SCOPE_read")); } @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() { this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/client").exchange() .expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("test"); assertThat(client.getAccessToken().getTokenValue()).isEqualTo("access-token"); assertThat(client.getRefreshToken()).isNull(); } @Test public void oauth2LoginWhenAuthoritiesSpecifiedThenGrantsAccess() { this.client .mutateWith(SecurityMockServerConfigurers.mockOAuth2Login() .authorities(new SimpleGrantedAuthority("SCOPE_admin"))) .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities()) .contains(new SimpleGrantedAuthority("SCOPE_admin")); } @Test public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() { this.client .mutateWith(SecurityMockServerConfigurers.mockOAuth2Login() .attributes((a) -> a.put("iss", "https://idp.example.org"))) .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org"); } @Test public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception { OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get() .uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getName()).isEqualTo("test-subject"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get() .uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client.getPrincipalName()).isEqualTo("test-subject"); } @Test public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception { OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"), Collections.singletonMap("sub", "subject"), "sub"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login() .attributes((a) -> a.put("subject", "foo")).oauth2User(oauth2User)).get().uri("/token").exchange() .expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject"); this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User) .attributes((a) -> a.put("sub", "bar"))).get().uri("/token").exchange().expectStatus().isOk(); token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar"); } @RestController static class OAuth2LoginController { volatile OAuth2AuthenticationToken token; volatile OAuth2AuthorizedClient authorizedClient; @GetMapping("/token") OAuth2AuthenticationToken token(OAuth2AuthenticationToken token) { this.token = token; return token; } @GetMapping("/client") String authorizedClient(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) { this.authorizedClient = authorizedClient; return authorizedClient.getPrincipalName(); } } }
7,682
45.005988
127
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurerOpaqueTokenTests.java
/* * Copyright 2002-2021 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.test.web.reactive.server; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.web.reactive.result.method.annotation.CurrentSecurityContextArgumentResolver; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; /** * @author Josh Cummings * @since 5.3 */ @ExtendWith(MockitoExtension.class) public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockServerConfigurersTests { private GrantedAuthority authority1 = new SimpleGrantedAuthority("one"); private GrantedAuthority authority2 = new SimpleGrantedAuthority("two"); private WebTestClient client = WebTestClient.bindToController(this.securityContextController) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .argumentResolvers((resolvers) -> resolvers .addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry()))) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockOpaqueTokenWhenUsingDefaultsThenBearerTokenAuthentication() { this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()).get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getToken()).isNotNull(); assertThat(token.getTokenAttributes().get(OAuth2TokenIntrospectionClaimNames.SUB)).isEqualTo("user"); } @Test public void mockOpaqueTokenWhenAuthoritiesThenBearerTokenAuthentication() { this.client .mutateWith( SecurityMockServerConfigurers.mockOpaqueToken().authorities(this.authority1, this.authority2)) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1, this.authority2); } @Test public void mockOpaqueTokenWhenAttributesThenBearerTokenAuthentication() { String sub = new String("my-subject"); this.client .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken() .attributes((attributes) -> attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, sub))) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); assertThat(token.getTokenAttributes().get(OAuth2TokenIntrospectionClaimNames.SUB)).isSameAs(sub); } @Test public void mockOpaqueTokenWhenPrincipalThenBearerTokenAuthentication() { OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(); this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal)).get().exchange() .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); assertThat(token.getPrincipal()).isSameAs(principal); } @Test public void mockOpaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() { OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals .active((a) -> a.put("scope", "user")); this.client .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken() .attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "foo")).principal(principal)) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()) .getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)) .isEqualTo(principal.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)); this.client .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal) .attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "bar"))) .get().exchange().expectStatus().isOk(); context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); token = (BearerTokenAuthentication) context.getAuthentication(); assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()) .getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)).isEqualTo("bar"); } }
6,707
50.206107
113
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersClassAnnotatedTests.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import java.security.Principal; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ @WithMockUser @ExtendWith(SpringExtension.class) @SecurityTestExecutionListeners public class SecurityMockServerConfigurersClassAnnotatedTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void wheMockUserWhenClassAnnotatedThenSuccess() { this.client.get().exchange().expectStatus().isOk().expectBody(String.class) .consumeWith((response) -> assertThat(response.getResponseBody()).contains("\"username\":\"user\"")); Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test @WithMockUser("method-user") public void withMockUserWhenClassAndMethodAnnotationThenMethodOverrides() { this.client.get().exchange().expectStatus().isOk().expectBody(String.class).consumeWith( (response) -> assertThat(response.getResponseBody()).contains("\"username\":\"method-user\"")); Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); this.controller.assertPrincipalIsEqualTo(authentication); } @Test public void withMockUserWhenMutateWithThenMustateWithOverrides() { this.client.mutateWith(SecurityMockServerConfigurers.mockUser("mutateWith-mockUser")).get().exchange() .expectStatus().isOk().expectBody(String.class) .consumeWith((response) -> assertThat(response.getResponseBody()) .contains("\"username\":\"mutateWith-mockUser\"")); Principal principal = this.controller.removePrincipal(); assertPrincipalCreatedFromUserDetails(principal, this.userBuilder.username("mutateWith-mockUser").build()); } }
3,417
42.820513
109
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersJwtTests.java
/* * Copyright 2002-2019 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.test.web.reactive.server; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.web.reactive.result.method.annotation.CurrentSecurityContextArgumentResolver; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jérôme Wacongne &lt;ch4mp&#64;c4-soft.com&gt; * @author Josh Cummings * @since 5.2 */ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerConfigurersTests { GrantedAuthority authority1 = new SimpleGrantedAuthority("AUTHORITY1"); GrantedAuthority authority2 = new SimpleGrantedAuthority("AUTHORITY2"); WebTestClient client = WebTestClient.bindToController(this.securityContextController) .webFilter(new SecurityContextServerWebExchangeWebFilter()) .argumentResolvers((resolvers) -> resolvers .addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry()))) .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication() { this.client.mutateWith(SecurityMockServerConfigurers.mockJwt()).get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication(); assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getToken()).isNotNull(); assertThat(token.getToken().getSubject()).isEqualTo("user"); assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none"); } @Test public void mockJwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() { String name = new String("user"); this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.subject(name))).get().exchange() .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication(); assertThat(token.getToken().getSubject()).isSameAs(name); } @Test public void mockJwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() { this.client.mutateWith(SecurityMockServerConfigurers.mockJwt() .jwt((jwt) -> jwt.claim("scope", "ignored authorities")).authorities(this.authority1, this.authority2)) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1, this.authority2); } @Test public void mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() { this.client .mutateWith( SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities"))) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly( new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities")); } @Test public void mockJwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() { this.client .mutateWith( SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities")) .authorities((jwt) -> Arrays.asList(this.authority1))) .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1); } @Test public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() { Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build(); this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken)).get().exchange() .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication(); assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user"); assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token"); assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1"); } }
6,177
48.031746
114
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/reactive/server/AbstractMockServerConfigurersTests.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import java.security.Principal; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.annotation.CurrentSecurityContext; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @author Josh Cummings * @since 5.0 */ abstract class AbstractMockServerConfigurersTests { protected PrincipalController controller = new PrincipalController(); protected SecurityContextController securityContextController = new SecurityContextController(); protected User.UserBuilder userBuilder = User.withUsername("user").password("password").roles("USER"); protected void assertPrincipalCreatedFromUserDetails(Principal principal, UserDetails originalUserDetails) { assertThat(principal).isInstanceOf(UsernamePasswordAuthenticationToken.class); UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) principal; assertThat(authentication.getCredentials()).isEqualTo(originalUserDetails.getPassword()); assertThat(authentication.getAuthorities()).containsOnlyElementsOf(originalUserDetails.getAuthorities()); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); assertThat(userDetails.getPassword()).isEqualTo(authentication.getCredentials()); assertThat(authentication.getAuthorities()).containsOnlyElementsOf(userDetails.getAuthorities()); } @RestController protected static class PrincipalController { volatile Principal principal; @RequestMapping("/**") public Principal get(Principal principal) { this.principal = principal; return principal; } public Principal removePrincipal() { Principal result = this.principal; this.principal = null; return result; } public void assertPrincipalIsEqualTo(Principal expected) { assertThat(this.principal).isEqualTo(expected); this.principal = null; } } @RestController protected static class SecurityContextController { volatile SecurityContext securityContext; @RequestMapping("/**") public SecurityContext get(@CurrentSecurityContext SecurityContext securityContext) { this.securityContext = securityContext; return securityContext; } public SecurityContext removeSecurityContext() { SecurityContext result = this.securityContext; this.securityContext = null; return result; } } }
3,377
33.469388
109
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java
/* * Copyright 2002-2022 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.test.web.support; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.context.DelegatingSecurityContextRepository; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @ExtendWith(MockitoExtension.class) public class WebTestUtilsTests { @Mock private SecurityContextRepository contextRepo; @Mock private CsrfTokenRepository csrfRepo; private MockHttpServletRequest request; private ConfigurableApplicationContext context; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); } @AfterEach public void cleanup() { if (this.context != null) { this.context.close(); } } @Test public void getCsrfTokenRepositorytNoWac() { assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test public void getCsrfTokenRepositorytNoSecurity() { loadConfig(Config.class); assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test public void getCsrfTokenRepositorytSecurityNoCsrf() { loadConfig(SecurityNoCsrfConfig.class); assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test public void getCsrfTokenRepositorytSecurityCustomRepo() { CustomSecurityConfig.CONTEXT_REPO = this.contextRepo; CustomSecurityConfig.CSRF_REPO = this.csrfRepo; loadConfig(CustomSecurityConfig.class); assertThat(WebTestUtils.getCsrfTokenRepository(this.request)).isSameAs(this.csrfRepo); } // getSecurityContextRepository @Test public void getSecurityContextRepositoryNoWac() { assertThat(WebTestUtils.getSecurityContextRepository(this.request)) .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test public void getSecurityContextRepositoryNoSecurity() { loadConfig(Config.class); assertThat(WebTestUtils.getSecurityContextRepository(this.request)) .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test public void getSecurityContextRepositorySecurityNoCsrf() { loadConfig(SecurityNoCsrfConfig.class); assertThat(WebTestUtils.getSecurityContextRepository(this.request)) .isInstanceOf(DelegatingSecurityContextRepository.class); } @Test public void getSecurityContextRepositorySecurityCustomRepo() { CustomSecurityConfig.CONTEXT_REPO = this.contextRepo; CustomSecurityConfig.CSRF_REPO = this.csrfRepo; loadConfig(CustomSecurityConfig.class); assertThat(WebTestUtils.getSecurityContextRepository(this.request)).isSameAs(this.contextRepo); } @Test public void setSecurityContextRepositoryWhenSecurityContextHolderFilter() { SecurityContextRepository expectedRepository = mock(SecurityContextRepository.class); loadConfig(SecurityContextHolderFilterConfig.class); // verify our configuration sets up to have SecurityContextHolderFilter and not // SecurityContextPersistenceFilter assertThat(WebTestUtils.findFilter(this.request, SecurityContextPersistenceFilter.class)).isNull(); assertThat(WebTestUtils.findFilter(this.request, SecurityContextHolderFilter.class)).isNotNull(); WebTestUtils.setSecurityContextRepository(this.request, expectedRepository); assertThat(WebTestUtils.getSecurityContextRepository(this.request)).isSameAs(expectedRepository); } // gh-3343 @Test public void findFilterNoMatchingFilters() { loadConfig(PartialSecurityConfig.class); assertThat(WebTestUtils.findFilter(this.request, SecurityContextPersistenceFilter.class)).isNull(); } @Test public void findFilterNoSpringSecurityFilterChainInContext() { loadConfig(NoSecurityConfig.class); CsrfFilter toFind = new CsrfFilter(new HttpSessionCsrfTokenRepository()); FilterChainProxy springSecurityFilterChain = new FilterChainProxy( new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, toFind)); this.request.getServletContext().setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, springSecurityFilterChain); assertThat(WebTestUtils.findFilter(this.request, toFind.getClass())).isEqualTo(toFind); } @Test public void findFilterExplicitWithSecurityFilterInContext() { loadConfig(SecurityConfigWithDefaults.class); CsrfFilter toFind = new CsrfFilter(new HttpSessionCsrfTokenRepository()); FilterChainProxy springSecurityFilterChain = new FilterChainProxy( new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, toFind)); this.request.getServletContext().setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, springSecurityFilterChain); assertThat(WebTestUtils.findFilter(this.request, toFind.getClass())).isSameAs(toFind); } private void loadConfig(Class<?> config) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(config); context.refresh(); this.context = context; this.request.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); } @Configuration static class Config { } @Configuration @EnableWebSecurity static class SecurityNoCsrfConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable(); return http.build(); } } @Configuration @EnableWebSecurity static class CustomSecurityConfig { static CsrfTokenRepository CSRF_REPO; static SecurityContextRepository CONTEXT_REPO; @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .csrf() .csrfTokenRepository(CSRF_REPO) .and() .securityContext() .securityContextRepository(CONTEXT_REPO); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity static class PartialSecurityConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .securityMatcher(new AntPathRequestMatcher("/willnotmatchthis")); return http.build(); // @formatter:on } } @Configuration static class NoSecurityConfig { } @Configuration @EnableWebSecurity static class SecurityConfigWithDefaults { } @Configuration @EnableWebSecurity static class SecurityContextHolderFilterConfig { @Bean DefaultSecurityFilterChain springSecurityFilter(HttpSecurity http) throws Exception { // @formatter:off http .securityContext((securityContext) -> securityContext.requireExplicitSave(true)); // @formatter:on return http.build(); } } }
8,852
32.534091
113
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.java
/* * Copyright 2002-2022 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.test.web.servlet.request; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; 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.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.SecurityFilterChain; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; 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.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.Config.class) @WebAppConfiguration public class SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @BeforeEach public void setup() { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build(); } // SEC-2593 @Test public void userRequestPostProcessorWorksWithStateless() throws Exception { this.mvc.perform(get("/").with(user("user"))).andExpect(status().is2xxSuccessful()); } // SEC-2593 @WithMockUser @Test public void withMockUserWorksWithStateless() throws Exception { this.mvc.perform(get("/")).andExpect(status().is2xxSuccessful()); } @Configuration @EnableWebSecurity @EnableWebMvc static class Config { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); return http.build(); // @formatter:on } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(); } @RestController static class Controller { @RequestMapping("/") String hello() { return "Hello"; } } } }
3,858
34.40367
110
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2LoginTests.java
/* * Copyright 2002-2022 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.test.web.servlet.request; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; 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.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.SecurityFilterChain; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; 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.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.mockito.Mockito.mock; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Login; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Tests for {@link SecurityMockMvcRequestPostProcessors#oauth2Login()} * * @author Josh Cummings * @since 5.3 */ @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration public class SecurityMockMvcRequestPostProcessorsOAuth2LoginTests { @Autowired WebApplicationContext context; MockMvc mvc; @BeforeEach public void setup() { // @formatter:off this.mvc = MockMvcBuilders .webAppContextSetup(this.context) .apply(springSecurity()) .build(); // @formatter:on } @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthentication() throws Exception { this.mvc.perform(get("/name").with(oauth2Login())).andExpect(content().string("user")); this.mvc.perform(get("/admin/id-token/name").with(oauth2Login())).andExpect(status().isForbidden()); } @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() throws Exception { this.mvc.perform(get("/client-id").with(oauth2Login())).andExpect(content().string("test-client")); } @Test public void oauth2LoginWhenAuthoritiesSpecifiedThenGrantsAccess() throws Exception { this.mvc.perform( get("/admin/scopes").with(oauth2Login().authorities(new SimpleGrantedAuthority("SCOPE_admin")))) .andExpect(content().string("[\"SCOPE_admin\"]")); } @Test public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() throws Exception { this.mvc.perform( get("/attributes/iss").with(oauth2Login().attributes((a) -> a.put("iss", "https://idp.example.org")))) .andExpect(content().string("https://idp.example.org")); } @Test public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception { OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute"); this.mvc.perform(get("/attributes/custom-attribute").with(oauth2Login().oauth2User(oauth2User))) .andExpect(content().string("test-subject")); this.mvc.perform(get("/name").with(oauth2Login().oauth2User(oauth2User))) .andExpect(content().string("test-subject")); this.mvc.perform(get("/client-name").with(oauth2Login().oauth2User(oauth2User))) .andExpect(content().string("test-subject")); } @Test public void oauth2LoginWhenClientRegistrationSpecifiedThenUses() throws Exception { this.mvc.perform(get("/client-id") .with(oauth2Login().clientRegistration(TestClientRegistrations.clientRegistration().build()))) .andExpect(content().string("client-id")); } @Test public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception { OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"), Collections.singletonMap("username", "user"), "username"); this.mvc.perform(get("/attributes/sub") .with(oauth2Login().attributes((a) -> a.put("sub", "bar")).oauth2User(oauth2User))) .andExpect(status().isOk()).andExpect(content().string("no-attribute")); this.mvc.perform(get("/attributes/sub") .with(oauth2Login().oauth2User(oauth2User).attributes((a) -> a.put("sub", "bar")))) .andExpect(content().string("bar")); } @Configuration @EnableWebSecurity @EnableWebMvc static class OAuth2LoginConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests((authorize) -> authorize .requestMatchers("/admin/**").hasAuthority("SCOPE_admin") .anyRequest().hasAuthority("SCOPE_read") ).oauth2Login(); return http.build(); // @formatter:on } @Bean ClientRegistrationRepository clientRegistrationRepository() { return mock(ClientRegistrationRepository.class); } @Bean OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository() { return mock(OAuth2AuthorizedClientRepository.class); } @RestController static class PrincipalController { @GetMapping("/name") String name(@AuthenticationPrincipal OAuth2User oauth2User) { return oauth2User.getName(); } @GetMapping("/client-id") String authorizedClient(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) { return authorizedClient.getClientRegistration().getClientId(); } @GetMapping("/client-name") String clientName(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) { return authorizedClient.getPrincipalName(); } @GetMapping("/attributes/{attribute}") String attributes(@AuthenticationPrincipal OAuth2User oauth2User, @PathVariable("attribute") String attribute) { return Optional.ofNullable((String) oauth2User.getAttribute(attribute)).orElse("no-attribute"); } @GetMapping("/admin/scopes") List<String> scopes( @AuthenticationPrincipal(expression = "authorities") Collection<GrantedAuthority> authorities) { return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); } } } }
8,408
39.427885
117
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/Sec2935Tests.java
/* * Copyright 2002-2022 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.test.web.servlet.request; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; 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.EnableWebSecurity; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.SecurityFilterChain; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; 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.user; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; 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; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author Rob Winch */ @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration public class Sec2935Tests { @Autowired WebApplicationContext context; MockMvc mvc; @BeforeEach public void setup() { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build(); } // SEC-2935 @Test public void postProcessorUserNoUser() throws Exception { this.mvc.perform(get("/admin/abc").with(user("user").roles("ADMIN", "USER"))).andExpect(status().isNotFound()) .andExpect(authenticated().withUsername("user")); this.mvc.perform(get("/admin/abc")).andExpect(status().isUnauthorized()).andExpect(unauthenticated()); } @Test public void postProcessorUserOtherUser() throws Exception { this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound()) .andExpect(authenticated().withUsername("user1")); this.mvc.perform(get("/admin/abc").with(user("user2").roles("USER"))).andExpect(status().isForbidden()) .andExpect(authenticated().withUsername("user2")); } @WithMockUser @Test public void postProcessorUserWithMockUser() throws Exception { this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound()) .andExpect(authenticated().withUsername("user1")); this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden()) .andExpect(authenticated().withUsername("user")); } // SEC-2941 @Test public void defaultRequest() throws Exception { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()) .defaultRequest(get("/").with(user("default"))).build(); this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound()) .andExpect(authenticated().withUsername("user1")); this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden()) .andExpect(authenticated().withUsername("default")); } @Disabled @WithMockUser @Test public void defaultRequestOverridesWithMockUser() throws Exception { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()) .defaultRequest(get("/").with(user("default"))).build(); this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound()) .andExpect(authenticated().withUsername("user1")); this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden()) .andExpect(authenticated().withUsername("default")); } @EnableWebSecurity @Configuration @EnableWebMvc static class Config { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .httpBasic(); return http.build(); // @formatter:on } @Autowired void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(); } } }
5,572
39.093525
115
java
null
spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java
/* * Copyright 2002-2019 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.test.web.servlet.request; import java.util.Arrays; import java.util.List; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; import org.springframework.security.config.BeanIds; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.security.test.web.support.WebTestUtils; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; /** * Tests for {@link SecurityMockMvcRequestPostProcessors#jwt} * * @author Jérôme Wacongne &lt;ch4mp&#64;c4-soft.com&gt; * @author Josh Cummings * @since 5.2 */ @ExtendWith(MockitoExtension.class) public class SecurityMockMvcRequestPostProcessorsJwtTests { @Captor private ArgumentCaptor<SecurityContext> contextCaptor; @Mock private SecurityContextRepository repository; private MockHttpServletRequest request; @Mock private GrantedAuthority authority1; @Mock private GrantedAuthority authority2; @BeforeEach public void setup() { SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(this.repository); MockServletContext servletContext = new MockServletContext(); servletContext.setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, new FilterChainProxy(new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, filter))); this.request = new MockHttpServletRequest(servletContext); WebTestUtils.setSecurityContextRepository(this.request, this.repository); } @AfterEach public void cleanup() { TestSecurityContextHolder.clearContext(); } @Test public void jwtWhenUsingDefaultsThenProducesDefaultJwtAuthentication() { jwt().postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication(); assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getToken()).isNotNull(); assertThat(token.getToken().getSubject()).isEqualTo("user"); assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none"); } @Test public void jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() { String name = new String("user"); jwt().jwt((jwt) -> jwt.subject(name)).postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication(); assertThat(token.getToken().getSubject()).isSameAs(name); } @Test public void jwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() { jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities")).authorities(this.authority1, this.authority2) .postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1, this.authority2); } @Test public void jwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() { jwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities")).postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly( new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities")); } @Test public void jwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() { jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities")) .authorities((jwt) -> Arrays.asList(this.authority1)).postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1); } @Test public void jwtWhenProvidingPreparedJwtThenUsesItForAuthentication() { Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build(); jwt().jwt(originalToken).postProcessRequest(this.request); verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class)); SecurityContext context = this.contextCaptor.getValue(); JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication(); assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user"); assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token"); assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1"); } }
7,338
43.478788
114
java