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/jackson2/DefaultSavedRequestMixin.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.springframework.security.web.savedrequest.DefaultSavedRequest; /** * Jackson mixin class to serialize/deserialize {@link DefaultSavedRequest}. This mixin * use {@link org.springframework.security.web.savedrequest.DefaultSavedRequest.Builder} * to deserialized json.In order to use this mixin class you also need to register * {@link CookieMixin}. * <p> * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebServletJackson2Module()); * </pre> * * @author Jitendra Singh * @since 4.2 * @see WebServletJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonDeserialize(builder = DefaultSavedRequest.Builder.class) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) abstract class DefaultSavedRequestMixin { @JsonInclude(JsonInclude.Include.NON_NULL) String matchingRequestParameterName; }
1,940
37.058824
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/DefaultCsrfTokenMixin.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.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.csrf.DefaultCsrfToken} serialization support. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebJackson2Module()); * </pre> * * @author Jitendra Singh * @since 4.2 * @see WebJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonIgnoreProperties(ignoreUnknown = true) class DefaultCsrfTokenMixin { /** * JsonCreator constructor needed by Jackson to create * {@link org.springframework.security.web.csrf.DefaultCsrfToken} object. * @param headerName the name of the header * @param parameterName the parameter name * @param token the CSRF token value */ @JsonCreator DefaultCsrfTokenMixin(@JsonProperty("headerName") String headerName, @JsonProperty("parameterName") String parameterName, @JsonProperty("token") String token) { } }
1,932
34.145455
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/WebAuthenticationDetailsMixin.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; 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.authentication.WebAuthenticationDetails}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebServletJackson2Module()); * </pre> * * @author Jitendra Singh * @since 4.2 * @see WebServletJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY) class WebAuthenticationDetailsMixin { @JsonCreator WebAuthenticationDetailsMixin(@JsonProperty("remoteAddress") String remoteAddress, @JsonProperty("sessionId") String sessionId) { } }
1,906
36.392157
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/PreAuthenticatedAuthenticationTokenDeserializer.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.jackson2; import java.io.IOException; import java.util.List; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.MissingNode; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** * Custom deserializer for {@link PreAuthenticatedAuthenticationToken}. At the time of * deserialization it will invoke suitable constructor depending on the value of * <b>authenticated</b> property. It will ensure that the token's state must not change. * <p> * This deserializer is already registered with * {@link PreAuthenticatedAuthenticationTokenMixin} but you can also registered it with * your own mixin class. * * @author Jitendra Singh * @since 4.2 * @see PreAuthenticatedAuthenticationTokenMixin */ class PreAuthenticatedAuthenticationTokenDeserializer extends JsonDeserializer<PreAuthenticatedAuthenticationToken> { private static final TypeReference<List<GrantedAuthority>> GRANTED_AUTHORITY_LIST = new TypeReference<List<GrantedAuthority>>() { }; /** * This method construct {@link PreAuthenticatedAuthenticationToken} object from * serialized json. * @param jp the JsonParser * @param ctxt the DeserializationContext * @return the user * @throws IOException if a exception during IO occurs * @throws JsonProcessingException if an error during JSON processing occurs */ @Override public PreAuthenticatedAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); JsonNode jsonNode = mapper.readTree(jp); Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean(); JsonNode principalNode = readJsonNode(jsonNode, "principal"); Object principal = (!principalNode.isObject()) ? principalNode.asText() : mapper.readValue(principalNode.traverse(mapper), Object.class); Object credentials = readJsonNode(jsonNode, "credentials").asText(); List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").traverse(mapper), GRANTED_AUTHORITY_LIST); PreAuthenticatedAuthenticationToken token = (!authenticated) ? new PreAuthenticatedAuthenticationToken(principal, credentials) : new PreAuthenticatedAuthenticationToken(principal, credentials, authorities); token.setDetails(readJsonNode(jsonNode, "details")); return token; } private JsonNode readJsonNode(JsonNode jsonNode, String field) { return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance(); } }
3,641
41.847059
130
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/PreAuthenticatedAuthenticationTokenMixin.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.jackson2.SimpleGrantedAuthorityMixin; /** * This mixin class is used to serialize / deserialize * {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken}. * This class register a custom deserializer * {@link PreAuthenticatedAuthenticationTokenDeserializer}. * * In order to use this mixin you'll need to add 3 more mixin classes. * <ol> * <li>{@link UnmodifiableSetMixin}</li> * <li>{@link SimpleGrantedAuthorityMixin}</li> * <li>{@link UserMixin}</li> * </ol> * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new CoreJackson2Module()); * </pre> * * @author Jitendra Singh * @since 4.2 * @see Webackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonDeserialize(using = PreAuthenticatedAuthenticationTokenDeserializer.class) abstract class PreAuthenticatedAuthenticationTokenMixin { }
2,106
36.625
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/SavedCookieMixin.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; 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.savedrequest.SavedCookie} serialization * support. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new WebServletJackson2Module()); * </pre> * * @author Jitendra Singh. * @since 4.2 * @see WebServletJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) abstract class SavedCookieMixin { @JsonCreator SavedCookieMixin(@JsonProperty("name") String name, @JsonProperty("value") String value, @JsonProperty("comment") String comment, @JsonProperty("domain") String domain, @JsonProperty("maxAge") int maxAge, @JsonProperty("path") String path, @JsonProperty("secure") boolean secure, @JsonProperty("version") int version) { } }
2,006
36.166667
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/WebJackson2Module.java
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.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.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.security.web.csrf.DefaultCsrfToken; /** * Jackson module for spring-security-web. This module register * {@link DefaultCsrfTokenMixin} and {@link PreAuthenticatedAuthenticationTokenMixin}. 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 WebJackson2Module()); * </pre> <b>Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list * of all security modules.</b> * * @author Jitendra Singh * @since 4.2 * @see SecurityJackson2Modules */ public class WebJackson2Module extends SimpleModule { public WebJackson2Module() { super(WebJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); } @Override public void setupModule(SetupContext context) { SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); context.setMixInAnnotations(DefaultCsrfToken.class, DefaultCsrfTokenMixin.class); context.setMixInAnnotations(PreAuthenticatedAuthenticationToken.class, PreAuthenticatedAuthenticationTokenMixin.class); } }
2,231
37.482759
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/HeaderWriterFilter.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.header; import java.io.IOException; import java.util.List; import jakarta.servlet.FilterChain; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.util.OnCommittedResponseWrapper; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * Filter implementation to add headers to the current response. Can be useful to add * certain headers which enable browser protection. Like X-Frame-Options, X-XSS-Protection * and X-Content-Type-Options. * * @author Marten Deinum * @author Josh Cummings * @author Ankur Pathak * @since 3.2 */ public class HeaderWriterFilter extends OncePerRequestFilter { /** * The {@link HeaderWriter} to write headers to the response. * {@see CompositeHeaderWriter} */ private final List<HeaderWriter> headerWriters; /** * Indicates whether to write the headers at the beginning of the request. */ private boolean shouldWriteHeadersEagerly = false; /** * Creates a new instance. * @param headerWriters the {@link HeaderWriter} instances to write out headers to the * {@link HttpServletResponse}. */ public HeaderWriterFilter(List<HeaderWriter> headerWriters) { Assert.notEmpty(headerWriters, "headerWriters cannot be null or empty"); this.headerWriters = headerWriters; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (this.shouldWriteHeadersEagerly) { doHeadersBefore(request, response, filterChain); } else { doHeadersAfter(request, response, filterChain); } } private void doHeadersBefore(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { writeHeaders(request, response); filterChain.doFilter(request, response); } private void doHeadersAfter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { HeaderWriterResponse headerWriterResponse = new HeaderWriterResponse(request, response); HeaderWriterRequest headerWriterRequest = new HeaderWriterRequest(request, headerWriterResponse); try { filterChain.doFilter(headerWriterRequest, headerWriterResponse); } finally { headerWriterResponse.writeHeaders(); } } void writeHeaders(HttpServletRequest request, HttpServletResponse response) { for (HeaderWriter writer : this.headerWriters) { writer.writeHeaders(request, response); } } /** * Allow writing headers at the beginning of the request. * @param shouldWriteHeadersEagerly boolean to allow writing headers at the beginning * of the request. * @since 5.2 */ public void setShouldWriteHeadersEagerly(boolean shouldWriteHeadersEagerly) { this.shouldWriteHeadersEagerly = shouldWriteHeadersEagerly; } class HeaderWriterResponse extends OnCommittedResponseWrapper { private final HttpServletRequest request; HeaderWriterResponse(HttpServletRequest request, HttpServletResponse response) { super(response); this.request = request; } @Override protected void onResponseCommitted() { writeHeaders(); this.disableOnResponseCommitted(); } protected void writeHeaders() { if (isDisableOnResponseCommitted()) { return; } HeaderWriterFilter.this.writeHeaders(this.request, getHttpResponse()); } private HttpServletResponse getHttpResponse() { return (HttpServletResponse) getResponse(); } } static class HeaderWriterRequest extends HttpServletRequestWrapper { private final HeaderWriterResponse response; HeaderWriterRequest(HttpServletRequest request, HeaderWriterResponse response) { super(request); this.response = response; } @Override public RequestDispatcher getRequestDispatcher(String path) { return new HeaderWriterRequestDispatcher(super.getRequestDispatcher(path), this.response); } } static class HeaderWriterRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate; private final HeaderWriterResponse response; HeaderWriterRequestDispatcher(RequestDispatcher delegate, HeaderWriterResponse response) { this.delegate = delegate; this.response = response; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.response.onResponseCommitted(); this.delegate.include(request, response); } } }
5,615
29.857143
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/Header.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header; import java.util.Arrays; import java.util.List; import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.Assert; /** * Represents a Header to be added to the {@link HttpServletResponse} */ public final class Header { private final String headerName; private final List<String> headerValues; /** * Creates a new instance * @param headerName the name of the header * @param headerValues the values of the header */ public Header(String headerName, String... headerValues) { Assert.hasText(headerName, "headerName is required"); Assert.notEmpty(headerValues, "headerValues cannot be null or empty"); Assert.noNullElements(headerValues, "headerValues cannot contain null values"); this.headerName = headerName; this.headerValues = Arrays.asList(headerValues); } /** * Gets the name of the header. Cannot be <code>null</code>. * @return the name of the header. */ public String getName() { return this.headerName; } /** * Gets the values of the header. Cannot be null, empty, or contain null values. * @return the values of the header */ public List<String> getValues() { return this.headerValues; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Header other = (Header) obj; if (!this.headerName.equals(other.headerName)) { return false; } return this.headerValues.equals(other.headerValues); } @Override public int hashCode() { return this.headerName.hashCode() + this.headerValues.hashCode(); } @Override public String toString() { return "Header [name: " + this.headerName + ", values: " + this.headerValues + "]"; } }
2,412
25.811111
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/HeaderWriter.java
/* * Copyright 2002-2013 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.header; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Contract for writing headers to a {@link HttpServletResponse} * * @author Marten Deinum * @author Rob Winch * @since 3.2 * @see HeaderWriterFilter */ public interface HeaderWriter { /** * Create a {@code Header} instance. * @param request the request * @param response the response */ void writeHeaders(HttpServletRequest request, HttpServletResponse response); }
1,160
28.025
77
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriter.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.header.writers; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * <p> * Provides support for <a href="https://www.w3.org/TR/referrer-policy/">Referrer * Policy</a>. * </p> * * <p> * The list of policies defined can be found at * <a href="https://www.w3.org/TR/referrer-policy/#referrer-policies">Referrer * Policies</a>. * </p> * * <p> * This implementation of {@link HeaderWriter} writes the following header: * </p> * <ul> * <li>Referrer-Policy</li> * </ul> * * <p> * By default, the Referrer-Policy header is not included in the response. Policy * <b>no-referrer</b> is used by default if no {@link ReferrerPolicy} is set. * </p> * * @author Eddú Meléndez * @author Kazuki Shimizu * @author Ankur Pathak * @since 4.2 */ public class ReferrerPolicyHeaderWriter implements HeaderWriter { private static final String REFERRER_POLICY_HEADER = "Referrer-Policy"; private ReferrerPolicy policy; /** * Creates a new instance. Default value: no-referrer. */ public ReferrerPolicyHeaderWriter() { this(ReferrerPolicy.NO_REFERRER); } /** * Creates a new instance. * @param policy a referrer policy * @throws IllegalArgumentException if policy is null */ public ReferrerPolicyHeaderWriter(ReferrerPolicy policy) { setPolicy(policy); } /** * Sets the policy to be used in the response header. * @param policy a referrer policy * @throws IllegalArgumentException if policy is null */ public void setPolicy(ReferrerPolicy policy) { Assert.notNull(policy, "policy can not be null"); this.policy = policy; } /** * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(HttpServletRequest, * HttpServletResponse) */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(REFERRER_POLICY_HEADER)) { response.setHeader(REFERRER_POLICY_HEADER, this.policy.getPolicy()); } } 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; } public static ReferrerPolicy get(String referrerPolicy) { return REFERRER_POLICIES.get(referrerPolicy); } } }
3,825
25.205479
94
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/CompositeHeaderWriter.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.header.writers; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * A {@link HeaderWriter} that delegates to several other {@link HeaderWriter}s. * * @author Ankur Pathak * @since 5.2 */ public class CompositeHeaderWriter implements HeaderWriter { private final List<HeaderWriter> headerWriters; /** * Creates a new instance. * @param headerWriters the {@link HeaderWriter} instances to write out headers to the * {@link HttpServletResponse}. */ public CompositeHeaderWriter(List<HeaderWriter> headerWriters) { Assert.notEmpty(headerWriters, "headerWriters cannot be empty"); this.headerWriters = headerWriters; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { this.headerWriters.forEach((headerWriter) -> headerWriter.writeHeaders(request, response)); } }
1,678
30.679245
93
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Provides support for * <a href="https://w3c.github.io/webappsec-permissions-policy//">Permisisons Policy</a>. * <p> * Permissions Policy allows web developers to selectively enable, disable, and modify the * behavior of certain APIs and web features in the browser. * <p> * A declaration of a permissions policy contains a set of security policies, each * responsible for declaring the restrictions for a particular feature type. * * @author Christophe Gilles * @since 5.5 */ public final class PermissionsPolicyHeaderWriter implements HeaderWriter { private static final String PERMISSIONS_POLICY_HEADER = "Permissions-Policy"; private String policy; /** * Create a new instance of {@link PermissionsPolicyHeaderWriter}. */ public PermissionsPolicyHeaderWriter() { } /** * Create a new instance of {@link PermissionsPolicyHeaderWriter} with supplied * security policy. * @param policy the security policy * @throws IllegalArgumentException if policy is {@code null} or empty */ public PermissionsPolicyHeaderWriter(String policy) { setPolicy(policy); } /** * Sets the policy to be used in the response header. * @param policy a permissions policy * @throws IllegalArgumentException if policy is null */ public void setPolicy(String policy) { Assert.hasLength(policy, "policy can not be null or empty"); this.policy = policy; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(PERMISSIONS_POLICY_HEADER)) { response.setHeader(PERMISSIONS_POLICY_HEADER, this.policy); } } @Override public String toString() { return getClass().getName() + " [policy=" + this.policy + "]"; } }
2,611
30.46988
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Inserts Cross-Origin-Embedder-Policy header. * * @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 CrossOriginEmbedderPolicyHeaderWriter implements HeaderWriter { private static final String EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; private CrossOriginEmbedderPolicy policy; /** * 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.policy = embedderPolicy; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.policy != null && !response.containsHeader(EMBEDDER_POLICY)) { response.addHeader(EMBEDDER_POLICY, this.policy.getPolicy()); } } 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; } public static CrossOriginEmbedderPolicy from(String embedderPolicy) { for (CrossOriginEmbedderPolicy policy : values()) { if (policy.getPolicy().equals(embedderPolicy)) { return policy; } } return null; } } }
2,460
27.952941
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * <p> * Provides support for <a href="https://www.w3.org/TR/CSP2/">Content Security Policy * (CSP) Level 2</a>. * </p> * * <p> * CSP provides a mechanism for web applications to mitigate content injection * vulnerabilities, such as cross-site scripting (XSS). CSP is a declarative policy that * allows web application authors to inform the client (user-agent) about the sources from * which the application expects to load resources. * </p> * * <p> * For example, a web application can declare that it only expects to load script from * specific, trusted sources. This declaration allows the client to detect and block * malicious scripts injected into the application by an attacker. * </p> * * <p> * A declaration of a security policy contains a set of security policy directives (for * example, script-src and object-src), each responsible for declaring the restrictions * for a particular resource type. The list of directives defined can be found at * <a href="https://www.w3.org/TR/CSP2/#directives">Directives</a>. * </p> * * <p> * Each directive has a name and value. For detailed syntax on writing security policies, * see <a href="https://www.w3.org/TR/CSP2/#syntax-and-algorithms">Syntax and * Algorithms</a>. * </p> * * <p> * This implementation of {@link HeaderWriter} writes one of the following headers: * </p> * <ul> * <li>Content-Security-Policy</li> * <li>Content-Security-Policy-Report-Only</li> * </ul> * * <p> * By default, the Content-Security-Policy header is included in the response. However, * calling {@link #setReportOnly(boolean)} with {@code true} will include the * Content-Security-Policy-Report-Only header in the response. <strong>NOTE:</strong> The * supplied security policy directive(s) will be used for whichever header is enabled * (included). * </p> * * <p> * <strong> CSP is not intended as a first line of defense against content injection * vulnerabilities. Instead, CSP is used to reduce the harm caused by content injection * attacks. As a first line of defense against content injection, web application authors * should validate their input and encode their output. </strong> * </p> * * @author Joe Grandja * @author Ankur Pathak * @since 4.1 */ public final class ContentSecurityPolicyHeaderWriter implements HeaderWriter { private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; private static final String CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only"; private static final String DEFAULT_SRC_SELF_POLICY = "default-src 'self'"; private String policyDirectives; private boolean reportOnly; /** * Creates a new instance. Default value: default-src 'self' */ public ContentSecurityPolicyHeaderWriter() { setPolicyDirectives(DEFAULT_SRC_SELF_POLICY); this.reportOnly = false; } /** * Creates a new instance * @param policyDirectives maps to {@link #setPolicyDirectives(String)} * @throws IllegalArgumentException if policyDirectives is null or empty */ public ContentSecurityPolicyHeaderWriter(String policyDirectives) { setPolicyDirectives(policyDirectives); this.reportOnly = false; } /** * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(jakarta.servlet.http.HttpServletRequest, * jakarta.servlet.http.HttpServletResponse) */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { String headerName = (!this.reportOnly) ? CONTENT_SECURITY_POLICY_HEADER : CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER; if (!response.containsHeader(headerName)) { response.setHeader(headerName, this.policyDirectives); } } /** * Sets the security policy directive(s) to be used in the response header. * @param policyDirectives the security policy directive(s) * @throws IllegalArgumentException if policyDirectives is null or empty */ public void setPolicyDirectives(String policyDirectives) { Assert.hasLength(policyDirectives, "policyDirectives cannot be null or empty"); this.policyDirectives = policyDirectives; } /** * If true, includes the Content-Security-Policy-Report-Only header in the response, * otherwise, defaults to the Content-Security-Policy header. * @param reportOnly set to true for reporting policy violations only */ public void setReportOnly(boolean reportOnly) { this.reportOnly = reportOnly; } @Override public String toString() { return getClass().getName() + " [policyDirectives=" + this.policyDirectives + "; reportOnly=" + this.reportOnly + "]"; } }
5,487
34.869281
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/XContentTypeOptionsHeaderWriter.java
/* * Copyright 2002-2013 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.header.writers; /** * A {@link StaticHeadersWriter} that inserts headers to prevent content sniffing. * Specifically the following headers are set: * <ul> * <li>X-Content-Type-Options: nosniff</li> * </ul> * * @author Rob Winch * @since 3.2 */ public final class XContentTypeOptionsHeaderWriter extends StaticHeadersWriter { /** * Creates a new instance */ public XContentTypeOptionsHeaderWriter() { super("X-Content-Type-Options", "nosniff"); } }
1,133
28.076923
82
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Inserts the 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 CrossOriginOpenerPolicyHeaderWriter implements HeaderWriter { private static final String OPENER_POLICY = "Cross-Origin-Opener-Policy"; private CrossOriginOpenerPolicy policy; /** * 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.policy = openerPolicy; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.policy != null && !response.containsHeader(OPENER_POLICY)) { response.addHeader(OPENER_POLICY, this.policy.getPolicy()); } } 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; } public static CrossOriginOpenerPolicy from(String openerPolicy) { for (CrossOriginOpenerPolicy policy : values()) { if (policy.getPolicy().equals(openerPolicy)) { return policy; } } return null; } } }
2,470
27.402299
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriter.java
/* * Copyright 2002-2013 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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Delegates to the provided {@link HeaderWriter} when * {@link RequestMatcher#matches(HttpServletRequest)} returns true. * * @author Rob Winch * @since 3.2 */ public final class DelegatingRequestMatcherHeaderWriter implements HeaderWriter { private final RequestMatcher requestMatcher; private final HeaderWriter delegateHeaderWriter; /** * Creates a new instance * @param requestMatcher the {@link RequestMatcher} to use. If returns true, the * delegateHeaderWriter will be invoked. * @param delegateHeaderWriter the {@link HeaderWriter} to invoke if the * {@link RequestMatcher} returns true. */ public DelegatingRequestMatcherHeaderWriter(RequestMatcher requestMatcher, HeaderWriter delegateHeaderWriter) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); Assert.notNull(delegateHeaderWriter, "delegateHeaderWriter cannot be null"); this.requestMatcher = requestMatcher; this.delegateHeaderWriter = delegateHeaderWriter; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.requestMatcher.matches(request)) { this.delegateHeaderWriter.writeHeaders(request, response); } } @Override public String toString() { return getClass().getName() + " [requestMatcher=" + this.requestMatcher + ", delegateHeaderWriter=" + this.delegateHeaderWriter + "]"; } }
2,330
33.791045
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/CacheControlHeadersWriter.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.header.writers; import java.util.ArrayList; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.web.header.Header; import org.springframework.security.web.header.HeaderWriter; /** * Inserts headers to prevent caching if no cache control headers have been specified. * Specifically it adds the following headers: * <ul> * <li>Cache-Control: no-cache, no-store, max-age=0, must-revalidate</li> * <li>Pragma: no-cache</li> * <li>Expires: 0</li> * </ul> * * @author Rob Winch * @since 3.2 */ public final class CacheControlHeadersWriter implements HeaderWriter { private static final String EXPIRES = "Expires"; private static final String PRAGMA = "Pragma"; private static final String CACHE_CONTROL = "Cache-Control"; private final HeaderWriter delegate; /** * Creates a new instance */ public CacheControlHeadersWriter() { this.delegate = new StaticHeadersWriter(createHeaders()); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (hasHeader(response, CACHE_CONTROL) || hasHeader(response, EXPIRES) || hasHeader(response, PRAGMA) || response.getStatus() == HttpStatus.NOT_MODIFIED.value()) { return; } this.delegate.writeHeaders(request, response); } private boolean hasHeader(HttpServletResponse response, String headerName) { return response.getHeader(headerName) != null; } private static List<Header> createHeaders() { List<Header> headers = new ArrayList<>(3); headers.add(new Header(CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")); headers.add(new Header(PRAGMA, "no-cache")); headers.add(new Header(EXPIRES, "0")); return headers; } }
2,490
30.1375
103
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Provides support for <a href="https://w3c.github.io/webappsec-clear-site-data/">Clear * Site Data</a>. * * <p> * Developers may instruct a user agent to clear various types of relevant data by * delivering a Clear-Site-Data HTTP response header in response to a request. * <p> * * <p> * Due to <a href="https://w3c.github.io/webappsec-clear-site-data/#incomplete">Incomplete * Clearing</a> section the header is only applied if the request is secure. * </p> * * @author Rafiullah Hamedy * @since 5.2 */ public final class ClearSiteDataHeaderWriter implements HeaderWriter { private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; private final Log logger = LogFactory.getLog(getClass()); private final RequestMatcher requestMatcher; private String headerValue; /** * <p> * Creates a new instance of {@link ClearSiteDataHeaderWriter} with given sources. The * constructor also initializes <b>requestMatcher</b> with a new instance of * <b>SecureRequestMatcher</b> to ensure that header is only applied if and when the * request is secure as per the <b>Incomplete Clearing</b> section. * </p> * @param directives (i.e. "cache", "cookies", "storage", "executionContexts" or "*") * @throws IllegalArgumentException if sources is null or empty. */ public ClearSiteDataHeaderWriter(Directive... directives) { Assert.notEmpty(directives, "directives cannot be empty or null"); this.requestMatcher = new SecureRequestMatcher(); this.headerValue = transformToHeaderValue(directives); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.requestMatcher.matches(request)) { if (!response.containsHeader(CLEAR_SITE_DATA_HEADER)) { response.setHeader(CLEAR_SITE_DATA_HEADER, this.headerValue); } } this.logger.debug( LogMessage.format("Not injecting Clear-Site-Data header since it did not match the requestMatcher %s", this.requestMatcher)); } 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(); } @Override public String toString() { return getClass().getName() + " [headerValue=" + this.headerValue + "]"; } /** * Represents the directive values expected by the {@link ClearSiteDataHeaderWriter}. */ 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 static final class SecureRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return request.isSecure(); } @Override public String toString() { return "Is Secure"; } } }
4,194
28.964286
106
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.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.header.writers; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Provides support for <a href="https://tools.ietf.org/html/rfc7469">HTTP Public Key * Pinning (HPKP)</a>. * * <p> * Since <a href="https://tools.ietf.org/html/rfc7469#section-4.1">Section 4.1</a> states * that a value on the order of 60 days (5,184,000 seconds) may be considered a good * balance, we use this value as the default. This can be customized using * {@link #setMaxAgeInSeconds(long)}. * </p> * * <p> * Because <a href="https://tools.ietf.org/html/rfc7469#appendix-B">Appendix B</a> * recommends that operators should first deploy public key pinning by using the * report-only mode, we opted to use this mode as default. This can be customized using * {@link #setReportOnly(boolean)}. * </p> * * <p> * Since we need to validate a certificate chain, the "Public-Key-Pins" or * "Public-Key-Pins-Report-Only" header will only be added when * {@link HttpServletRequest#isSecure()} returns {@code true}. * </p> * * <p> * To set the pins you first need to extract the public key information from your * certificate or key file and encode them using Base64. The following commands will help * you extract the Base64 encoded information from a key file, a certificate signing * request, or a certificate. * * <pre> * openssl rsa -in my-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 * * openssl req -in my-signing-request.csr -pubkey -noout | openssl rsa -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 * * openssl x509 -in my-certificate.crt -pubkey -noout | openssl rsa -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 * </pre> * * * The following command will extract the Base64 encoded information for a website. * * <pre> * openssl s_client -servername www.example.com -connect www.example.com:443 | openssl x509 -pubkey -noout | openssl rsa -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 * </pre> * </p> * * <p> * Some examples: * * <pre> * Public-Key-Pins: max-age=3000; * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" * * Public-Key-Pins: max-age=5184000; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=" * * Public-Key-Pins: max-age=5184000; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="; * report-uri="https://example.com/pkp-report" * * Public-Key-Pins-Report-Only: max-age=5184000; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="; * report-uri="https://other.example.net/pkp-report" * * Public-Key-Pins: max-age=5184000; * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="; * includeSubDomains * </pre> * </p> * * @author Tim Ysewyn * @author Ankur Pathak * @since 4.1 * @deprecated see <a href= * "https://owasp.org/www-community/controls/Certificate_and_Public_Key_Pinning">Certificate * and Public Key Pinning</a> for more context */ @Deprecated public final class HpkpHeaderWriter implements HeaderWriter { private static final long DEFAULT_MAX_AGE_SECONDS = 5184000; private static final String HPKP_HEADER_NAME = "Public-Key-Pins"; private static final String HPKP_RO_HEADER_NAME = "Public-Key-Pins-Report-Only"; private final Log logger = LogFactory.getLog(getClass()); private final RequestMatcher requestMatcher = new SecureRequestMatcher(); private Map<String, String> pins = new LinkedHashMap<>(); private long maxAgeInSeconds; private boolean includeSubDomains; private boolean reportOnly; private URI reportUri; private String hpkpHeaderValue; /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} * @param reportOnly maps to {@link #setReportOnly(boolean)} */ public HpkpHeaderWriter(long maxAgeInSeconds, boolean includeSubDomains, boolean reportOnly) { this.maxAgeInSeconds = maxAgeInSeconds; this.includeSubDomains = includeSubDomains; this.reportOnly = reportOnly; updateHpkpHeaderValue(); } /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} */ public HpkpHeaderWriter(long maxAgeInSeconds, boolean includeSubDomains) { this(maxAgeInSeconds, includeSubDomains, true); } /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} */ public HpkpHeaderWriter(long maxAgeInSeconds) { this(maxAgeInSeconds, false); } /** * Creates a new instance */ public HpkpHeaderWriter() { this(DEFAULT_MAX_AGE_SECONDS); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!this.requestMatcher.matches(request)) { this.logger.debug("Not injecting HPKP header since it wasn't a secure connection"); return; } if (this.pins.isEmpty()) { this.logger.debug("Not injecting HPKP header since there aren't any pins"); return; } String headerName = (this.reportOnly) ? HPKP_RO_HEADER_NAME : HPKP_HEADER_NAME; if (!response.containsHeader(headerName)) { response.setHeader(headerName, this.hpkpHeaderValue); } } /** * <p> * Sets the value for the pin- directive of the Public-Key-Pins header. * </p> * * <p> * The pin directive specifies a way for web host operators to indicate a * cryptographic identity that should be bound to a given web host. See * <a href="https://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for * additional details. * </p> * * <p> * To get a pin of * * Public-Key-Pins: pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" * * Use * * <code> * Map&lt;String, String&gt; pins = new HashMap&lt;String, String&gt;(); * pins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256"); * pins.put("E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=", "sha256"); * </code> * </p> * @param pins the map of base64-encoded SPKI fingerprint &amp; cryptographic hash * algorithm pairs. * @throws IllegalArgumentException if pins is null */ public void setPins(Map<String, String> pins) { Assert.notNull(pins, "pins cannot be null"); this.pins = pins; updateHpkpHeaderValue(); } /** * <p> * Adds a list of SHA256 hashed pins for the pin- directive of the Public-Key-Pins * header. * </p> * * <p> * The pin directive specifies a way for web host operators to indicate a * cryptographic identity that should be bound to a given web host. See * <a href="https://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for * additional details. * </p> * * <p> * To get a pin of * * Public-Key-Pins-Report-Only: * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" * * Use * * HpkpHeaderWriter hpkpHeaderWriter = new HpkpHeaderWriter(); * hpkpHeaderWriter.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM", * "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="); * </p> * @param pins a list of base64-encoded SPKI fingerprints. * @throws IllegalArgumentException if a pin is null */ public void addSha256Pins(String... pins) { for (String pin : pins) { Assert.notNull(pin, "pin cannot be null"); this.pins.put(pin, "sha256"); } updateHpkpHeaderValue(); } /** * <p> * Sets the value (in seconds) for the max-age directive of the Public-Key-Pins * header. The default is 60 days. * </p> * * <p> * This instructs browsers how long they should regard the host (from whom the message * was received) as a known pinned host. See * <a href="https://tools.ietf.org/html/rfc7469#section-2.1.2">Section 2.1.2</a> for * additional details. * </p> * * <p> * To get a header like * * Public-Key-Pins-Report-Only: max-age=2592000; * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" * * Use * * HpkpHeaderWriter hpkpHeaderWriter = new HpkpHeaderWriter(); * hpkpHeaderWriter.setMaxAgeInSeconds(TimeUnit.DAYS.toSeconds(30)); * </p> * @param maxAgeInSeconds the maximum amount of time (in seconds) to regard the host * as a known pinned host. (i.e. TimeUnit.DAYS.toSeconds(30) would set this to 30 * days) * @throws IllegalArgumentException if maxAgeInSeconds is negative */ public void setMaxAgeInSeconds(long maxAgeInSeconds) { Assert.isTrue(maxAgeInSeconds > 0, () -> "maxAgeInSeconds must be non-negative. Got " + maxAgeInSeconds); this.maxAgeInSeconds = maxAgeInSeconds; updateHpkpHeaderValue(); } /** * <p> * If true, the pinning policy applies to this pinned host as well as any subdomains * of the host's domain name. The default is false. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.3">Section 2.1.3</a> * for additional details. * </p> * * <p> * To get a header like * * Public-Key-Pins-Report-Only: max-age=5184000; * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; includeSubDomains * * you should set this to true. * </p> * @param includeSubDomains true to include subdomains, else false */ public void setIncludeSubDomains(boolean includeSubDomains) { this.includeSubDomains = includeSubDomains; updateHpkpHeaderValue(); } /** * <p> * To get a Public-Key-Pins header you should set this to false, otherwise the header * will be Public-Key-Pins-Report-Only. When in report-only mode, the browser should * not terminate the connection with the server. By default this is true. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc7469#section-2.1">Section 2.1</a> for * additional details. * </p> * * <p> * To get a header like * * Public-Key-Pins: max-age=5184000; * pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" * * you should the this to false. * </p> * @param reportOnly true to report only, else false */ public void setReportOnly(boolean reportOnly) { this.reportOnly = reportOnly; } /** * <p> * Sets the URI to which the browser should report pin validation failures. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a> * for additional details. * </p> * * <p> * To get a header like * * Public-Key-Pins-Report-Only: max-age=5184000; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="; * report-uri="https://other.example.net/pkp-report" * * Use * * HpkpHeaderWriter hpkpHeaderWriter = new HpkpHeaderWriter(); * hpkpHeaderWriter.setReportUri(new URI("https://other.example.net/pkp-report")); * </p> * @param reportUri the URI where the browser should send the report to. */ public void setReportUri(URI reportUri) { this.reportUri = reportUri; updateHpkpHeaderValue(); } /** * <p> * Sets the URI to which the browser should report pin validation failures. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a> * for additional details. * </p> * * <p> * To get a header like * * Public-Key-Pins-Report-Only: max-age=5184000; * pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; * pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="; * report-uri="https://other.example.net/pkp-report" * * Use * * HpkpHeaderWriter hpkpHeaderWriter = new HpkpHeaderWriter(); * hpkpHeaderWriter.setReportUri("https://other.example.net/pkp-report"); * </p> * @param reportUri the URI where the browser should send the report to. * @throws IllegalArgumentException if the reportUri is not a valid URI */ public void setReportUri(String reportUri) { try { this.reportUri = new URI(reportUri); updateHpkpHeaderValue(); } catch (URISyntaxException ex) { throw new IllegalArgumentException(ex); } } private void updateHpkpHeaderValue() { String headerValue = "max-age=" + this.maxAgeInSeconds; for (Map.Entry<String, String> pin : this.pins.entrySet()) { headerValue += " ; pin-" + pin.getValue() + "=\"" + pin.getKey() + "\""; } if (this.reportUri != null) { headerValue += " ; report-uri=\"" + this.reportUri.toString() + "\""; } if (this.includeSubDomains) { headerValue += " ; includeSubDomains"; } this.hpkpHeaderValue = headerValue; } private static final class SecureRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return request.isSecure(); } @Override public String toString() { return "Is Secure"; } } }
14,476
31.028761
193
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/StaticHeadersWriter.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.header.writers; import java.util.Collections; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.Header; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * {@code HeaderWriter} implementation which writes the same {@code Header} instance. * * @author Marten Deinum * @author Rob Winch * @author Ankur Pathak * @since 3.2 */ public class StaticHeadersWriter implements HeaderWriter { private final List<Header> headers; /** * Creates a new instance * @param headers the {@link Header} instances to use */ public StaticHeadersWriter(List<Header> headers) { Assert.notEmpty(headers, "headers cannot be null or empty"); this.headers = headers; } /** * Creates a new instance with a single header * @param headerName the name of the header * @param headerValues the values for the header */ public StaticHeadersWriter(String headerName, String... headerValues) { this(Collections.singletonList(new Header(headerName, headerValues))); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { for (Header header : this.headers) { if (!response.containsHeader(header.getName())) { for (String value : header.getValues()) { response.addHeader(header.getName(), value); } } } } @Override public String toString() { return getClass().getName() + " [headers=" + this.headers + "]"; } }
2,225
28.289474
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Renders the <a href= * "https://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx" * >X-XSS-Protection header</a>. * * @author Rob Winch * @author Ankur Pathak * @author Daniel Garnier-Moiroux * @since 3.2 */ public final class XXssProtectionHeaderWriter implements HeaderWriter { private static final String XSS_PROTECTION_HEADER = "X-XSS-Protection"; private HeaderValue headerValue; /** * Create a new instance */ public XXssProtectionHeaderWriter() { this.headerValue = HeaderValue.DISABLED; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(XSS_PROTECTION_HEADER)) { response.setHeader(XSS_PROTECTION_HEADER, this.headerValue.toString()); } } /** * Sets the value of the X-XSS-PROTECTION header. * <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 header value * @throws IllegalArgumentException when headerValue is null * @since 5.8 */ public void setHeaderValue(HeaderValue headerValue) { Assert.notNull(headerValue, "headerValue cannot be null"); this.headerValue = headerValue; } /** * 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; } public static HeaderValue from(String headerValue) { for (HeaderValue value : values()) { if (value.toString().equals(headerValue)) { return value; } } return null; } @Override public String toString() { return this.value; } } @Override public String toString() { return getClass().getName() + " [headerValue=" + this.headerValue + "]"; } }
3,421
26.15873
148
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/HstsHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Provides support for <a href="https://tools.ietf.org/html/rfc6797">HTTP Strict * Transport Security (HSTS)</a>. * * <p> * By default the expiration is one year, subdomains will be included and preload will not * be included. This can be customized using {@link #setMaxAgeInSeconds(long)}, * {@link #setIncludeSubDomains(boolean)} and {@link #setPreload(boolean)} respectively. * </p> * * <p> * Since <a href="https://tools.ietf.org/html/rfc6797#section-7.2">section 7.2</a> states * that HSTS Host MUST NOT include the STS header in HTTP responses, the default behavior * is that the "Strict-Transport-Security" will only be added when * {@link HttpServletRequest#isSecure()} returns {@code true} . At times this may need to * be customized. For example, in some situations where SSL termination is used, something * else may be used to determine if SSL was used. For these circumstances, * {@link #setRequestMatcher(RequestMatcher)} can be invoked with a custom * {@link RequestMatcher}. * </p> * * <p> * See <a href="https://hstspreload.org/">Website hstspreload.org</a> for additional * details on HSTS preload. * </p> * * @author Rob Winch * @author Ankur Pathak * @since 3.2 */ public final class HstsHeaderWriter implements HeaderWriter { private static final long DEFAULT_MAX_AGE_SECONDS = 31536000; private static final String HSTS_HEADER_NAME = "Strict-Transport-Security"; private final Log logger = LogFactory.getLog(getClass()); private RequestMatcher requestMatcher; private long maxAgeInSeconds; private boolean includeSubDomains; private boolean preload; private String hstsHeaderValue; /** * Creates a new instance * @param requestMatcher maps to {@link #setRequestMatcher(RequestMatcher)} * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} * @param preload maps to {@link #setPreload(boolean)} * @since 5.2.0 */ public HstsHeaderWriter(RequestMatcher requestMatcher, long maxAgeInSeconds, boolean includeSubDomains, boolean preload) { this.requestMatcher = requestMatcher; this.maxAgeInSeconds = maxAgeInSeconds; this.includeSubDomains = includeSubDomains; this.preload = preload; updateHstsHeaderValue(); } /** * Creates a new instance * @param requestMatcher maps to {@link #setRequestMatcher(RequestMatcher)} * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} */ public HstsHeaderWriter(RequestMatcher requestMatcher, long maxAgeInSeconds, boolean includeSubDomains) { this(requestMatcher, maxAgeInSeconds, includeSubDomains, false); } /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} * @param preload maps to {@link #setPreload(boolean)} * @since 5.2.0 */ public HstsHeaderWriter(long maxAgeInSeconds, boolean includeSubDomains, boolean preload) { this(new SecureRequestMatcher(), maxAgeInSeconds, includeSubDomains, preload); } /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} */ public HstsHeaderWriter(long maxAgeInSeconds, boolean includeSubDomains) { this(new SecureRequestMatcher(), maxAgeInSeconds, includeSubDomains, false); } /** * Creates a new instance * @param maxAgeInSeconds maps to {@link #setMaxAgeInSeconds(long)} */ public HstsHeaderWriter(long maxAgeInSeconds) { this(new SecureRequestMatcher(), maxAgeInSeconds, true, false); } /** * Creates a new instance * @param includeSubDomains maps to {@link #setIncludeSubDomains(boolean)} */ public HstsHeaderWriter(boolean includeSubDomains) { this(new SecureRequestMatcher(), DEFAULT_MAX_AGE_SECONDS, includeSubDomains, false); } /** * Creates a new instance */ public HstsHeaderWriter() { this(DEFAULT_MAX_AGE_SECONDS); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!this.requestMatcher.matches(request)) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Not injecting HSTS header since it did not match request to [%s]", this.requestMatcher)); } return; } if (!response.containsHeader(HSTS_HEADER_NAME)) { response.setHeader(HSTS_HEADER_NAME, this.hstsHeaderValue); } } /** * Sets the {@link RequestMatcher} used to determine if the * "Strict-Transport-Security" should be added. If true the header is added, else the * header is not added. By default the header is added when * {@link HttpServletRequest#isSecure()} returns true. * @param requestMatcher the {@link RequestMatcher} to use. * @throws IllegalArgumentException if {@link RequestMatcher} is null */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } /** * <p> * Sets the value (in seconds) for the max-age directive of the * Strict-Transport-Security header. The default is one year. * </p> * * <p> * This instructs browsers how long to remember to keep this domain as a known HSTS * Host. See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.1">Section * 6.1.1</a> for additional details. * </p> * @param maxAgeInSeconds the maximum amount of time (in seconds) to consider this * domain as a known HSTS Host. * @throws IllegalArgumentException if maxAgeInSeconds is negative */ public void setMaxAgeInSeconds(long maxAgeInSeconds) { Assert.isTrue(maxAgeInSeconds >= 0, () -> "maxAgeInSeconds must be non-negative. Got " + maxAgeInSeconds); this.maxAgeInSeconds = maxAgeInSeconds; updateHstsHeaderValue(); } /** * <p> * If true, subdomains should be considered HSTS Hosts too. The default is true. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a> * for additional details. * </p> * @param includeSubDomains true to include subdomains, else false */ public void setIncludeSubDomains(boolean includeSubDomains) { this.includeSubDomains = includeSubDomains; updateHstsHeaderValue(); } /** * <p> * If true, preload will be included in HSTS Header. The default is false. * </p> * * <p> * See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a> * for additional details. * </p> * @param preload true to include preload, else false * @since 5.2.0 */ public void setPreload(boolean preload) { this.preload = preload; updateHstsHeaderValue(); } private void updateHstsHeaderValue() { String headerValue = "max-age=" + this.maxAgeInSeconds; if (this.includeSubDomains) { headerValue += " ; includeSubDomains"; } if (this.preload) { headerValue += " ; preload"; } this.hstsHeaderValue = headerValue; } private static final class SecureRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return request.isSecure(); } @Override public String toString() { return "Is Secure"; } } }
8,420
32.153543
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Provides support for <a href="https://wicg.github.io/feature-policy/">Feature * Policy</a>. * <p> * Feature Policy allows web developers to selectively enable, disable, and modify the * behavior of certain APIs and web features in the browser. * <p> * A declaration of a feature policy contains a set of security policy directives, each * responsible for declaring the restrictions for a particular feature type. * * @author Vedran Pavic * @author Ankur Pathak * @since 5.1 */ public final class FeaturePolicyHeaderWriter implements HeaderWriter { private static final String FEATURE_POLICY_HEADER = "Feature-Policy"; private String policyDirectives; /** * Create a new instance of {@link FeaturePolicyHeaderWriter} with supplied security * policy directive(s). * @param policyDirectives the security policy directive(s) * @throws IllegalArgumentException if policyDirectives is {@code null} or empty */ public FeaturePolicyHeaderWriter(String policyDirectives) { setPolicyDirectives(policyDirectives); } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(FEATURE_POLICY_HEADER)) { response.setHeader(FEATURE_POLICY_HEADER, this.policyDirectives); } } /** * Set the security policy directive(s) to be used in the response header. * @param policyDirectives the security 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; } @Override public String toString() { return getClass().getName() + " [policyDirectives=" + this.policyDirectives + "]"; } }
2,708
33.730769
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriter.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.header.writers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * Inserts Cross-Origin-Resource-Policy header * * @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 CrossOriginResourcePolicyHeaderWriter implements HeaderWriter { private static final String RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; private CrossOriginResourcePolicy policy; /** * Sets the {@link CrossOriginResourcePolicy} value to be used in the * {@code Cross-Origin-Resource-Policy} header * @param resourcePolicy the {@link CrossOriginResourcePolicy} to use */ public void setPolicy(CrossOriginResourcePolicy resourcePolicy) { Assert.notNull(resourcePolicy, "resourcePolicy cannot be null"); this.policy = resourcePolicy; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.policy != null && !response.containsHeader(RESOURCE_POLICY)) { response.addHeader(RESOURCE_POLICY, this.policy.getPolicy()); } } 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; } public static CrossOriginResourcePolicy from(String resourcePolicy) { for (CrossOriginResourcePolicy policy : values()) { if (policy.getPolicy().equals(resourcePolicy)) { return policy; } } return null; } } }
2,486
27.586207
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AllowFromStrategy.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header.writers.frameoptions; import jakarta.servlet.http.HttpServletRequest; /** * Strategy interfaces used by the {@code FrameOptionsHeaderWriter} to determine the * actual value to use for the X-Frame-Options header when using the ALLOW-FROM directive. * * @author Marten Deinum * @since 3.2 * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public interface AllowFromStrategy { /** * Gets the value for ALLOW-FROM excluding the ALLOW-FROM. For example, the result * might be "https://example.com/". * @param request the {@link HttpServletRequest} * @return the value for ALLOW-FROM or null if no header should be added for this * request. */ String getAllowFromValue(HttpServletRequest request); }
1,640
35.466667
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriter.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.header.writers.frameoptions; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * {@code HeaderWriter} implementation for the X-Frame-Options headers. When using the * ALLOW-FROM directive the actual value is determined by a {@code AllowFromStrategy}. * * @author Marten Deinum * @author Rob Winch * @author Ankur Pathak * @since 3.2 * @see AllowFromStrategy */ public final class XFrameOptionsHeaderWriter implements HeaderWriter { public static final String XFRAME_OPTIONS_HEADER = "X-Frame-Options"; private final AllowFromStrategy allowFromStrategy; private final XFrameOptionsMode frameOptionsMode; /** * Creates an instance with {@link XFrameOptionsMode#DENY} */ public XFrameOptionsHeaderWriter() { this(XFrameOptionsMode.DENY); } /** * Creates a new instance * @param frameOptionsMode the {@link XFrameOptionsMode} to use. If using * {@link XFrameOptionsMode#ALLOW_FROM}, use * {@link #XFrameOptionsHeaderWriter(AllowFromStrategy)} instead. */ public XFrameOptionsHeaderWriter(XFrameOptionsMode frameOptionsMode) { Assert.notNull(frameOptionsMode, "frameOptionsMode cannot be null"); Assert.isTrue(!XFrameOptionsMode.ALLOW_FROM.equals(frameOptionsMode), "ALLOW_FROM requires an AllowFromStrategy. Please use " + "FrameOptionsHeaderWriter(AllowFromStrategy allowFromStrategy) instead"); this.frameOptionsMode = frameOptionsMode; this.allowFromStrategy = null; } /** * Creates a new instance with {@link XFrameOptionsMode#ALLOW_FROM}. * @param allowFromStrategy the strategy for determining what the value for ALLOW_FROM * is. * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public XFrameOptionsHeaderWriter(AllowFromStrategy allowFromStrategy) { Assert.notNull(allowFromStrategy, "allowFromStrategy cannot be null"); this.frameOptionsMode = XFrameOptionsMode.ALLOW_FROM; this.allowFromStrategy = allowFromStrategy; } /** * Writes the X-Frame-Options header value, overwritting any previous value. * @param request the servlet request * @param response the servlet response */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (XFrameOptionsMode.ALLOW_FROM.equals(this.frameOptionsMode)) { String allowFromValue = this.allowFromStrategy.getAllowFromValue(request); if (XFrameOptionsMode.DENY.getMode().equals(allowFromValue)) { if (!response.containsHeader(XFRAME_OPTIONS_HEADER)) { response.setHeader(XFRAME_OPTIONS_HEADER, XFrameOptionsMode.DENY.getMode()); } } else if (allowFromValue != null) { if (!response.containsHeader(XFRAME_OPTIONS_HEADER)) { response.setHeader(XFRAME_OPTIONS_HEADER, XFrameOptionsMode.ALLOW_FROM.getMode() + " " + allowFromValue); } } } else { response.setHeader(XFRAME_OPTIONS_HEADER, this.frameOptionsMode.getMode()); } } /** * The possible values for the X-Frame-Options header. * * @author Rob Winch * @since 3.2 */ public enum XFrameOptionsMode { DENY("DENY"), SAMEORIGIN("SAMEORIGIN"), /** * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated ALLOW_FROM("ALLOW-FROM"); private final String mode; XFrameOptionsMode(String mode) { this.mode = mode; } /** * Gets the mode for the X-Frame-Options header value. For example, DENY, * SAMEORIGIN, ALLOW-FROM. Cannot be null. * @return the mode for the X-Frame-Options header value. */ private String getMode() { return this.mode; } } }
4,812
31.965753
124
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategy.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header.writers.frameoptions; import java.net.URI; import jakarta.servlet.http.HttpServletRequest; /** * Simple implementation of the {@code AllowFromStrategy} * * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public final class StaticAllowFromStrategy implements AllowFromStrategy { private final URI uri; public StaticAllowFromStrategy(URI uri) { this.uri = uri; } @Override public String getAllowFromValue(HttpServletRequest request) { return this.uri.toString(); } }
1,407
29.608696
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategy.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header.writers.frameoptions; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Base class for AllowFromStrategy implementations which use a request parameter to * retrieve the origin. By default the parameter named <code>x-frames-allow-from</code> is * read from the request. * * @author Marten Deinum * @since 3.2 * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public abstract class AbstractRequestParameterAllowFromStrategy implements AllowFromStrategy { private static final String DEFAULT_ORIGIN_REQUEST_PARAMETER = "x-frames-allow-from"; private String allowFromParameterName = DEFAULT_ORIGIN_REQUEST_PARAMETER; /** Logger for use by subclasses */ protected final Log log = LogFactory.getLog(getClass()); AbstractRequestParameterAllowFromStrategy() { } @Override public String getAllowFromValue(HttpServletRequest request) { String allowFromOrigin = request.getParameter(this.allowFromParameterName); this.log.debug(LogMessage.format("Supplied origin '%s'", allowFromOrigin)); if (StringUtils.hasText(allowFromOrigin) && allowed(allowFromOrigin)) { return allowFromOrigin; } return "DENY"; } /** * Sets the HTTP parameter used to retrieve the value for the origin that is allowed * from. The value of the parameter should be a valid URL. The default parameter name * is "x-frames-allow-from". * @param allowFromParameterName the name of the HTTP parameter to */ public void setAllowFromParameterName(String allowFromParameterName) { Assert.notNull(allowFromParameterName, "allowFromParameterName cannot be null"); this.allowFromParameterName = allowFromParameterName; } /** * Method to be implemented by base classes, used to determine if the supplied origin * is allowed. * @param allowFromOrigin the supplied origin * @return <code>true</code> if the supplied origin is allowed. */ protected abstract boolean allowed(String allowFromOrigin); }
3,060
36.329268
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/WhiteListedAllowFromStrategy.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header.writers.frameoptions; import java.util.Collection; import org.springframework.util.Assert; /** * Implementation which checks the supplied origin against a list of allowed origins. * * @author Marten Deinum * @since 3.2 * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public final class WhiteListedAllowFromStrategy extends AbstractRequestParameterAllowFromStrategy { private final Collection<String> allowed; /** * Creates a new instance * @param allowed the origins that are allowed. */ public WhiteListedAllowFromStrategy(Collection<String> allowed) { Assert.notEmpty(allowed, "Allowed origins cannot be empty."); this.allowed = allowed; } @Override protected boolean allowed(String allowFromOrigin) { return this.allowed.contains(allowFromOrigin); } }
1,710
31.283019
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategy.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.header.writers.frameoptions; import java.util.regex.Pattern; import org.springframework.util.Assert; /** * Implementation which uses a regular expression to validate the supplied origin. If the * value of the HTTP parameter matches the pattern, then the result will be ALLOW-FROM * &lt;paramter-value&gt;. * * @author Marten Deinum * @since 3.2 * @deprecated ALLOW-FROM is an obsolete directive that no longer works in modern * browsers. Instead use Content-Security-Policy with the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> * directive. */ @Deprecated public final class RegExpAllowFromStrategy extends AbstractRequestParameterAllowFromStrategy { private final Pattern pattern; /** * Creates a new instance * @param pattern the Pattern to compare against the HTTP parameter value. If the * pattern matches, the domain will be allowed, else denied. */ public RegExpAllowFromStrategy(String pattern) { Assert.hasText(pattern, "Pattern cannot be empty."); this.pattern = Pattern.compile(pattern); } @Override protected boolean allowed(String allowFromOrigin) { return this.pattern.matcher(allowFromOrigin).matches(); } }
1,911
33.142857
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/WebInvocationPrivilegeEvaluator.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access; import org.springframework.security.core.Authentication; /** * Allows users to determine whether they have privileges for a given web URI. * * @author Luke Taylor * @since 3.0 */ public interface WebInvocationPrivilegeEvaluator { /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI. * @param uri the URI excluding the context path (a default context path setting will * be used) */ boolean isAllowed(String uri, Authentication authentication); /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI, with the given . * <p> * Note the default implementation of <tt>FilterInvocationSecurityMetadataSource</tt> * disregards the <code>contextPath</code> when evaluating which secure object * metadata applies to a given request URI, so generally the <code>contextPath</code> * is unimportant unless you are using a custom * <code>FilterInvocationSecurityMetadataSource</code>. * @param uri the URI excluding the context path * @param contextPath the context path (may be null). * @param method the HTTP method (or null, for any method) * @param authentication the <tt>Authentication</tt> instance whose authorities should * be used in evaluation whether access should be granted. * @return true if access is allowed, false if denied */ boolean isAllowed(String contextPath, String uri, String method, Authentication authentication); }
2,220
38.660714
97
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Access-control related classes and packages. */ package org.springframework.security.web.access;
728
33.714286
75
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluator.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.access; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; import org.springframework.web.context.ServletContextAware; /** * An implementation of {@link WebInvocationPrivilegeEvaluator} which delegates the checks * to an instance of {@link AuthorizationManager} * * @author Marcus Da Coregio * @since 5.5.5 */ public final class AuthorizationManagerWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator, ServletContextAware { private final AuthorizationManager<HttpServletRequest> authorizationManager; private ServletContext servletContext; public AuthorizationManagerWebInvocationPrivilegeEvaluator( AuthorizationManager<HttpServletRequest> authorizationManager) { Assert.notNull(authorizationManager, "authorizationManager cannot be null"); this.authorizationManager = authorizationManager; } @Override public boolean isAllowed(String uri, Authentication authentication) { return isAllowed(null, uri, null, authentication); } @Override public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext); AuthorizationDecision decision = this.authorizationManager.check(() -> authentication, filterInvocation.getHttpRequest()); return decision == null || decision.isGranted(); } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } }
2,511
35.941176
106
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/NoOpAccessDeniedHandler.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.access; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; /** * An {@link AccessDeniedHandler} implementation that does nothing. * * @author Marcus da Coregio * @since 6.2 */ public class NoOpAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { } }
1,284
29.595238
86
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluator.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.access; import java.util.Collection; import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; import org.springframework.web.context.ServletContextAware; /** * Allows users to determine whether they have privileges for a given web URI. * * @author Ben Alex * @author Luke Taylor * @since 3.0 * @deprecated Use {@link AuthorizationManagerWebInvocationPrivilegeEvaluator} instead */ @Deprecated public class DefaultWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator, ServletContextAware { protected static final Log logger = LogFactory.getLog(DefaultWebInvocationPrivilegeEvaluator.class); private final AbstractSecurityInterceptor securityInterceptor; private ServletContext servletContext; public DefaultWebInvocationPrivilegeEvaluator(AbstractSecurityInterceptor securityInterceptor) { Assert.notNull(securityInterceptor, "SecurityInterceptor cannot be null"); Assert.isTrue(FilterInvocation.class.equals(securityInterceptor.getSecureObjectClass()), "AbstractSecurityInterceptor does not support FilterInvocations"); Assert.notNull(securityInterceptor.getAccessDecisionManager(), "AbstractSecurityInterceptor must provide a non-null AccessDecisionManager"); this.securityInterceptor = securityInterceptor; } /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI. * @param uri the URI excluding the context path (a default context path setting will * be used) */ @Override public boolean isAllowed(String uri, Authentication authentication) { return isAllowed(null, uri, null, authentication); } /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI, with the given . * <p> * Note the default implementation of <tt>FilterInvocationSecurityMetadataSource</tt> * disregards the <code>contextPath</code> when evaluating which secure object * metadata applies to a given request URI, so generally the <code>contextPath</code> * is unimportant unless you are using a custom * <code>FilterInvocationSecurityMetadataSource</code>. * @param uri the URI excluding the context path * @param contextPath the context path (may be null, in which case a default value * will be used). * @param method the HTTP method (or null, for any method) * @param authentication the <tt>Authentication</tt> instance whose authorities should * be used in evaluation whether access should be granted. * @return true if access is allowed, false if denied */ @Override public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { Assert.notNull(uri, "uri parameter is required"); FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext); Collection<ConfigAttribute> attributes = this.securityInterceptor.obtainSecurityMetadataSource() .getAttributes(filterInvocation); if (attributes == null) { return (!this.securityInterceptor.isRejectPublicInvocations()); } if (authentication == null) { return false; } try { this.securityInterceptor.getAccessDecisionManager().decide(authentication, filterInvocation, attributes); return true; } catch (AccessDeniedException ex) { logger.debug(LogMessage.format("%s denied for %s", filterInvocation, authentication), ex); return false; } } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } }
4,719
39.689655
117
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandler.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.access; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map.Entry; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * An {@link AccessDeniedHandler} that delegates to other {@link AccessDeniedHandler} * instances based upon the type of {@link HttpServletRequest} passed into * {@link #handle(HttpServletRequest, HttpServletResponse, AccessDeniedException)}. * * @author Josh Cummings * @since 5.1 * */ public final class RequestMatcherDelegatingAccessDeniedHandler implements AccessDeniedHandler { private final LinkedHashMap<RequestMatcher, AccessDeniedHandler> handlers; private final AccessDeniedHandler defaultHandler; /** * Creates a new instance * @param handlers a map of {@link RequestMatcher}s to {@link AccessDeniedHandler}s * that should be used. Each is considered in the order they are specified and only * the first {@link AccessDeniedHandler} is used. * @param defaultHandler the default {@link AccessDeniedHandler} that should be used * if none of the matchers match. */ public RequestMatcherDelegatingAccessDeniedHandler(LinkedHashMap<RequestMatcher, AccessDeniedHandler> handlers, AccessDeniedHandler defaultHandler) { Assert.notEmpty(handlers, "handlers cannot be null or empty"); Assert.notNull(defaultHandler, "defaultHandler cannot be null"); this.handlers = new LinkedHashMap<>(handlers); this.defaultHandler = defaultHandler; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { for (Entry<RequestMatcher, AccessDeniedHandler> entry : this.handlers.entrySet()) { RequestMatcher matcher = entry.getKey(); if (matcher.matches(request)) { AccessDeniedHandler handler = entry.getValue(); handler.handle(request, response, accessDeniedException); return; } } this.defaultHandler.handle(request, response, accessDeniedException); } }
2,913
36.844156
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/DelegatingAccessDeniedHandler.java
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map.Entry; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.Assert; /** * An {@link AccessDeniedHandler} that delegates to other {@link AccessDeniedHandler} * instances based upon the type of {@link AccessDeniedException} passed into * {@link #handle(HttpServletRequest, HttpServletResponse, AccessDeniedException)}. * * @author Rob Winch * @since 3.2 * */ public final class DelegatingAccessDeniedHandler implements AccessDeniedHandler { private final LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers; private final AccessDeniedHandler defaultHandler; /** * Creates a new instance * @param handlers a map of the {@link AccessDeniedException} class to the * {@link AccessDeniedHandler} that should be used. Each is considered in the order * they are specified and only the first {@link AccessDeniedHandler} is ued. * @param defaultHandler the default {@link AccessDeniedHandler} that should be used * if none of the handlers matches. */ public DelegatingAccessDeniedHandler( LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers, AccessDeniedHandler defaultHandler) { Assert.notEmpty(handlers, "handlers cannot be null or empty"); Assert.notNull(defaultHandler, "defaultHandler cannot be null"); this.handlers = handlers; this.defaultHandler = defaultHandler; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { for (Entry<Class<? extends AccessDeniedException>, AccessDeniedHandler> entry : this.handlers.entrySet()) { Class<? extends AccessDeniedException> handlerClass = entry.getKey(); if (handlerClass.isAssignableFrom(accessDeniedException.getClass())) { AccessDeniedHandler handler = entry.getValue(); handler.handle(request, response, accessDeniedException); return; } } this.defaultHandler.handle(request, response, accessDeniedException); } }
2,958
37.428571
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/ObservationMarkingAccessDeniedHandler.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.access; import java.io.IOException; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; public final class ObservationMarkingAccessDeniedHandler implements AccessDeniedHandler { private final ObservationRegistry registry; public ObservationMarkingAccessDeniedHandler(ObservationRegistry registry) { this.registry = registry; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException { Observation observation = this.registry.getCurrentObservation(); if (observation != null) { observation.error(exception); } } }
1,558
32.170213
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java
/* * Copyright 2004-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.access; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.core.log.LogMessage; import org.springframework.security.access.AccessDeniedException; 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.core.SpringSecurityMessageSource; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.util.ThrowableAnalyzer; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * Handles any <code>AccessDeniedException</code> and <code>AuthenticationException</code> * thrown within the filter chain. * <p> * This filter is necessary because it provides the bridge between Java exceptions and * HTTP responses. It is solely concerned with maintaining the user interface. This filter * does not do any actual security enforcement. * <p> * If an {@link AuthenticationException} is detected, the filter will launch the * <code>authenticationEntryPoint</code>. This allows common handling of authentication * failures originating from any subclass of * {@link org.springframework.security.access.intercept.AbstractSecurityInterceptor}. * <p> * If an {@link AccessDeniedException} is detected, the filter will determine whether or * not the user is an anonymous user. If they are an anonymous user, the * <code>authenticationEntryPoint</code> will be launched. If they are not an anonymous * user, the filter will delegate to the * {@link org.springframework.security.web.access.AccessDeniedHandler}. By default the * filter will use * {@link org.springframework.security.web.access.AccessDeniedHandlerImpl}. * <p> * To use this filter, it is necessary to specify the following properties: * <ul> * <li><code>authenticationEntryPoint</code> indicates the handler that should commence * the authentication process if an <code>AuthenticationException</code> is detected. Note * that this may also switch the current protocol from http to https for an SSL * login.</li> * <li><tt>requestCache</tt> determines the strategy used to save a request during the * authentication process in order that it may be retrieved and reused once the user has * authenticated. The default implementation is {@link HttpSessionRequestCache}.</li> * </ul> * * @author Ben Alex * @author colin sampaleanu */ public class ExceptionTranslationFilter extends GenericFilterBean implements MessageSourceAware { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandlerImpl(); private AuthenticationEntryPoint authenticationEntryPoint; private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); private RequestCache requestCache = new HttpSessionRequestCache(); protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint) { this(authenticationEntryPoint, new HttpSessionRequestCache()); } public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint, RequestCache requestCache) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); Assert.notNull(requestCache, "requestCache cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; this.requestCache = requestCache; } @Override public void afterPropertiesSet() { Assert.notNull(this.authenticationEntryPoint, "authenticationEntryPoint must be specified"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } catch (IOException ex) { throw ex; } catch (Exception ex) { // Try to extract a SpringSecurityException from the stacktrace Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex); RuntimeException securityException = (AuthenticationException) this.throwableAnalyzer .getFirstThrowableOfType(AuthenticationException.class, causeChain); if (securityException == null) { securityException = (AccessDeniedException) this.throwableAnalyzer .getFirstThrowableOfType(AccessDeniedException.class, causeChain); } if (securityException == null) { rethrow(ex); } if (response.isCommitted()) { throw new ServletException("Unable to handle the Spring Security Exception " + "because the response is already committed.", ex); } handleSpringSecurityException(request, response, chain, securityException); } } private void rethrow(Exception ex) throws ServletException { // Rethrow ServletExceptions and RuntimeExceptions as-is if (ex instanceof ServletException) { throw (ServletException) ex; } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } // Wrap other Exceptions. This shouldn't actually happen // as we've already covered all the possibilities for doFilter throw new RuntimeException(ex); } public AuthenticationEntryPoint getAuthenticationEntryPoint() { return this.authenticationEntryPoint; } protected AuthenticationTrustResolver getAuthenticationTrustResolver() { return this.authenticationTrustResolver; } private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException { if (exception instanceof AuthenticationException) { handleAuthenticationException(request, response, chain, (AuthenticationException) exception); } else if (exception instanceof AccessDeniedException) { handleAccessDeniedException(request, response, chain, (AccessDeniedException) exception); } } private void handleAuthenticationException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException exception) throws ServletException, IOException { this.logger.trace("Sending to authentication entry point since authentication failed", exception); sendStartAuthentication(request, response, chain, exception); } private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AccessDeniedException exception) throws ServletException, IOException { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication); if (isAnonymous || this.authenticationTrustResolver.isRememberMe(authentication)) { if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied", authentication), exception); } sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException( this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource"))); } else { if (logger.isTraceEnabled()) { logger.trace( LogMessage.format("Sending %s to access denied handler since access is denied", authentication), exception); } this.accessDeniedHandler.handle(request, response, exception); } } protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { // SEC-112: Clear the SecurityContextHolder's Authentication, as the // existing Authentication is no longer considered valid SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); this.securityContextHolderStrategy.setContext(context); this.requestCache.saveRequest(request, response); this.authenticationEntryPoint.commence(request, response, reason); } public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "AccessDeniedHandler required"); this.accessDeniedHandler = accessDeniedHandler; } public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver) { Assert.notNull(authenticationTrustResolver, "authenticationTrustResolver must not be null"); this.authenticationTrustResolver = authenticationTrustResolver; } public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer) { Assert.notNull(throwableAnalyzer, "throwableAnalyzer must not be null"); this.throwableAnalyzer = throwableAnalyzer; } /** * @since 5.5 */ @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Default implementation of <code>ThrowableAnalyzer</code> which is capable of also * unwrapping <code>ServletException</code>s. */ private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { super.initExtractorMap(); registerExtractor(ServletException.class, (throwable) -> { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class); return ((ServletException) throwable).getRootCause(); }); } } }
12,099
42.52518
116
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandlerImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.WebAttributes; import org.springframework.util.Assert; /** * Base implementation of {@link AccessDeniedHandler}. * <p> * This implementation sends a 403 (SC_FORBIDDEN) HTTP error code. In addition, if an * {@link #errorPage} is defined, the implementation will perform a request dispatcher * "forward" to the specified error page view. Being a "forward", the * <code>SecurityContextHolder</code> will remain populated. This is of benefit if the * view (or a tag library or macro) wishes to access the * <code>SecurityContextHolder</code>. The request scope will also be populated with the * exception itself, available from the key {@link WebAttributes#ACCESS_DENIED_403}. * * @author Ben Alex */ public class AccessDeniedHandlerImpl implements AccessDeniedHandler { protected static final Log logger = LogFactory.getLog(AccessDeniedHandlerImpl.class); private String errorPage; @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { if (response.isCommitted()) { logger.trace("Did not write to response since already committed"); return; } if (this.errorPage == null) { logger.debug("Responding with 403 status code"); response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase()); return; } // Put exception into request scope (perhaps of use to a view) request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException); // Set the 403 status code. response.setStatus(HttpStatus.FORBIDDEN.value()); // forward to error page. if (logger.isDebugEnabled()) { logger.debug(LogMessage.format("Forwarding to %s with status code 403", this.errorPage)); } request.getRequestDispatcher(this.errorPage).forward(request, response); } /** * The error page to use. Must begin with a "/" and is interpreted relative to the * current context root. * @param errorPage the dispatcher path to display * @throws IllegalArgumentException if the argument doesn't comply with the above * limitations */ public void setErrorPage(String errorPage) { Assert.isTrue(errorPage == null || errorPage.startsWith("/"), "errorPage must begin with '/'"); this.errorPage = errorPage; } }
3,425
37.931818
97
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/CompositeAccessDeniedHandler.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.access; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; public final class CompositeAccessDeniedHandler implements AccessDeniedHandler { private Collection<AccessDeniedHandler> handlers; public CompositeAccessDeniedHandler(AccessDeniedHandler... handlers) { this(Arrays.asList(handlers)); } public CompositeAccessDeniedHandler(Collection<AccessDeniedHandler> handlers) { this.handlers = new ArrayList<>(handlers); } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { for (AccessDeniedHandler handler : this.handlers) { handler.handle(request, response, accessDeniedException); } } }
1,664
31.647059
86
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.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.access; import java.util.Collections; import java.util.List; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.RequestMatcherEntry; import org.springframework.util.Assert; import org.springframework.web.context.ServletContextAware; /** * A {@link WebInvocationPrivilegeEvaluator} which delegates to a list of * {@link WebInvocationPrivilegeEvaluator} based on a * {@link org.springframework.security.web.util.matcher.RequestMatcher} evaluation * * @author Marcus Da Coregio * @since 5.5.5 */ public final class RequestMatcherDelegatingWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator, ServletContextAware { private final List<RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>>> delegates; private ServletContext servletContext; public RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( List<RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>>> requestMatcherPrivilegeEvaluatorsEntries) { Assert.notNull(requestMatcherPrivilegeEvaluatorsEntries, "requestMatcherPrivilegeEvaluators cannot be null"); for (RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> entry : requestMatcherPrivilegeEvaluatorsEntries) { Assert.notNull(entry.getRequestMatcher(), "requestMatcher cannot be null"); Assert.notNull(entry.getEntry(), "webInvocationPrivilegeEvaluators cannot be null"); } this.delegates = requestMatcherPrivilegeEvaluatorsEntries; } /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI. * <p> * Uses the provided URI in the * {@link org.springframework.security.web.util.matcher.RequestMatcher#matches(HttpServletRequest)} * for every {@code RequestMatcher} configured. If no {@code RequestMatcher} is * matched, or if there is not an available {@code WebInvocationPrivilegeEvaluator}, * returns {@code true}. * @param uri the URI excluding the context path (a default context path setting will * be used) * @return true if access is allowed, false if denied */ @Override public boolean isAllowed(String uri, Authentication authentication) { List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = getDelegate(null, uri, null); if (privilegeEvaluators.isEmpty()) { return true; } for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) { boolean isAllowed = evaluator.isAllowed(uri, authentication); if (!isAllowed) { return false; } } return true; } /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI. * <p> * Uses the provided URI in the * {@link org.springframework.security.web.util.matcher.RequestMatcher#matches(HttpServletRequest)} * for every {@code RequestMatcher} configured. If no {@code RequestMatcher} is * matched, or if there is not an available {@code WebInvocationPrivilegeEvaluator}, * returns {@code true}. * @param uri the URI excluding the context path (a default context path setting will * be used) * @param contextPath the context path (may be null, in which case a default value * will be used). * @param method the HTTP method (or null, for any method) * @param authentication the <tt>Authentication</tt> instance whose authorities should * be used in evaluation whether access should be granted. * @return true if access is allowed, false if denied */ @Override public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = getDelegate(contextPath, uri, method); if (privilegeEvaluators.isEmpty()) { return true; } for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) { boolean isAllowed = evaluator.isAllowed(contextPath, uri, method, authentication); if (!isAllowed) { return false; } } return true; } private List<WebInvocationPrivilegeEvaluator> getDelegate(String contextPath, String uri, String method) { FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext); for (RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate : this.delegates) { if (delegate.getRequestMatcher().matches(filterInvocation.getHttpRequest())) { return delegate.getEntry(); } } return Collections.emptyList(); } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } }
5,406
39.654135
117
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandler.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; /** * Used by {@link ExceptionTranslationFilter} to handle an * <code>AccessDeniedException</code>. * * @author Ben Alex */ public interface AccessDeniedHandler { /** * Handles an access denied failure. * @param request that resulted in an <code>AccessDeniedException</code> * @param response so that the user agent can be advised of the failure * @param accessDeniedException that caused the invocation * @throws IOException in the event of an IOException * @throws ServletException in the event of a ServletException */ void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException; }
1,615
33.382979
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/DefaultHttpSecurityExpressionHandler.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.access.expression; import java.util.function.Supplier; import org.springframework.expression.EvaluationContext; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.security.access.expression.AbstractSecurityExpressionHandler; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.access.expression.SecurityExpressionOperations; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.core.Authentication; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; import org.springframework.util.Assert; /** * A {@link SecurityExpressionHandler} that uses a {@link RequestAuthorizationContext} to * create a {@link WebSecurityExpressionRoot}. * * @author Evgeniy Cheban * @since 5.8 */ public class DefaultHttpSecurityExpressionHandler extends AbstractSecurityExpressionHandler<RequestAuthorizationContext> implements SecurityExpressionHandler<RequestAuthorizationContext> { private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); private String defaultRolePrefix = "ROLE_"; @Override public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, RequestAuthorizationContext context) { WebSecurityExpressionRoot root = createSecurityExpressionRoot(authentication, context); StandardEvaluationContext ctx = new StandardEvaluationContext(root); ctx.setBeanResolver(getBeanResolver()); context.getVariables().forEach(ctx::setVariable); return ctx; } @Override protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, RequestAuthorizationContext context) { return createSecurityExpressionRoot(() -> authentication, context); } private WebSecurityExpressionRoot createSecurityExpressionRoot(Supplier<Authentication> authentication, RequestAuthorizationContext context) { WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(authentication, context.getRequest()); root.setRoleHierarchy(getRoleHierarchy()); root.setPermissionEvaluator(getPermissionEvaluator()); root.setTrustResolver(this.trustResolver); root.setDefaultRolePrefix(this.defaultRolePrefix); return root; } /** * Sets the {@link AuthenticationTrustResolver} to be used. The default is * {@link AuthenticationTrustResolverImpl}. * @param trustResolver the {@link AuthenticationTrustResolver} to use */ public void setTrustResolver(AuthenticationTrustResolver trustResolver) { Assert.notNull(trustResolver, "trustResolver cannot be null"); this.trustResolver = trustResolver; } /** * Sets the default prefix to be added to * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)} * or * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}. * For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the * role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default). * @param defaultRolePrefix the default prefix to add to roles. The default is * "ROLE_". */ public void setDefaultRolePrefix(String defaultRolePrefix) { Assert.notNull(defaultRolePrefix, "defaultRolePrefix cannot be null"); this.defaultRolePrefix = defaultRolePrefix; } }
4,186
41.72449
120
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Implementation of web security expressions. */ package org.springframework.security.web.access.expression;
738
34.190476
75
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessor.java
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.expression; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.expression.EvaluationContext; import org.springframework.security.web.FilterInvocation; /** * Exposes URI template variables as variables on the {@link EvaluationContext}. For * example, the pattern "/user/{username}/**" would expose a variable named username based * on the current URI. * * <p> * NOTE: This API is intentionally kept package scope as it may change in the future. It * may be nice to allow users to augment expressions and queries * </p> * * @author Rob Winch * @since 4.1 */ abstract class AbstractVariableEvaluationContextPostProcessor implements EvaluationContextPostProcessor<FilterInvocation> { @Override public final EvaluationContext postProcess(EvaluationContext context, FilterInvocation invocation) { return new VariableEvaluationContext(context, invocation.getHttpRequest()); } abstract Map<String, String> extractVariables(HttpServletRequest request); /** * {@link DelegatingEvaluationContext} to expose variable. */ class VariableEvaluationContext extends DelegatingEvaluationContext { private final HttpServletRequest request; private Map<String, String> variables; VariableEvaluationContext(EvaluationContext delegate, HttpServletRequest request) { super(delegate); this.request = request; } @Override public Object lookupVariable(String name) { Object result = super.lookupVariable(name); if (result != null) { return result; } if (this.variables == null) { this.variables = extractVariables(this.request); } return this.variables.get(name); } } }
2,347
29.102564
101
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionVoter.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.access.expression; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.expression.EvaluationContext; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.expression.ExpressionUtils; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; /** * Voter which handles web authorisation decisions. * * @author Luke Taylor * @since 3.0 * @deprecated Use {@link WebExpressionAuthorizationManager} instead */ @Deprecated public class WebExpressionVoter implements AccessDecisionVoter<FilterInvocation> { private final Log logger = LogFactory.getLog(getClass()); private SecurityExpressionHandler<FilterInvocation> expressionHandler = new DefaultWebSecurityExpressionHandler(); @Override public int vote(Authentication authentication, FilterInvocation filterInvocation, Collection<ConfigAttribute> attributes) { Assert.notNull(authentication, "authentication must not be null"); Assert.notNull(filterInvocation, "filterInvocation must not be null"); Assert.notNull(attributes, "attributes must not be null"); WebExpressionConfigAttribute webExpressionConfigAttribute = findConfigAttribute(attributes); if (webExpressionConfigAttribute == null) { this.logger .trace("Abstained since did not find a config attribute of instance WebExpressionConfigAttribute"); return ACCESS_ABSTAIN; } EvaluationContext ctx = webExpressionConfigAttribute.postProcess( this.expressionHandler.createEvaluationContext(authentication, filterInvocation), filterInvocation); boolean granted = ExpressionUtils.evaluateAsBoolean(webExpressionConfigAttribute.getAuthorizeExpression(), ctx); if (granted) { return ACCESS_GRANTED; } this.logger.trace("Voted to deny authorization"); return ACCESS_DENIED; } private WebExpressionConfigAttribute findConfigAttribute(Collection<ConfigAttribute> attributes) { for (ConfigAttribute attribute : attributes) { if (attribute instanceof WebExpressionConfigAttribute) { return (WebExpressionConfigAttribute) attribute; } } return null; } @Override public boolean supports(ConfigAttribute attribute) { return attribute instanceof WebExpressionConfigAttribute; } @Override public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } public void setExpressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler) { this.expressionHandler = expressionHandler; } }
3,464
36.258065
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionRoot.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.access.expression; import java.util.function.Supplier; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.IpAddressMatcher; /** * @author Luke Taylor * @author Evgeniy Cheban * @since 3.0 */ public class WebSecurityExpressionRoot extends SecurityExpressionRoot { /** * Allows direct access to the request object */ public final HttpServletRequest request; public WebSecurityExpressionRoot(Authentication a, FilterInvocation fi) { this(() -> a, fi.getRequest()); } /** * Creates an instance for the given {@link Supplier} of the {@link Authentication} * and {@link HttpServletRequest}. * @param authentication the {@link Supplier} of the {@link Authentication} to use * @param request the {@link HttpServletRequest} to use * @since 5.8 */ public WebSecurityExpressionRoot(Supplier<Authentication> authentication, HttpServletRequest request) { super(authentication); this.request = request; } /** * Takes a specific IP address or a range 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. * @return true if the IP address of the current request is in the required range. */ public boolean hasIpAddress(String ipAddress) { IpAddressMatcher matcher = new IpAddressMatcher(ipAddress); return matcher.matches(this.request); } }
2,291
32.217391
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionAuthorizationManager.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.access.expression; import java.util.function.Supplier; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.security.access.expression.ExpressionUtils; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.authorization.ExpressionAuthorizationDecision; import org.springframework.security.core.Authentication; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; import org.springframework.util.Assert; /** * An expression-based {@link AuthorizationManager} that determines the access by * evaluating the provided expression. * * @author Evgeniy Cheban * @since 5.8 */ public final class WebExpressionAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> { private SecurityExpressionHandler<RequestAuthorizationContext> expressionHandler = new DefaultHttpSecurityExpressionHandler(); private Expression expression; /** * Creates an instance. * @param expressionString the raw expression string to parse */ public WebExpressionAuthorizationManager(String expressionString) { Assert.hasText(expressionString, "expressionString cannot be empty"); this.expression = this.expressionHandler.getExpressionParser().parseExpression(expressionString); } /** * Sets the {@link SecurityExpressionHandler} to be used. The default is * {@link DefaultHttpSecurityExpressionHandler}. * @param expressionHandler the {@link SecurityExpressionHandler} to use */ public void setExpressionHandler(SecurityExpressionHandler<RequestAuthorizationContext> expressionHandler) { Assert.notNull(expressionHandler, "expressionHandler cannot be null"); this.expressionHandler = expressionHandler; this.expression = expressionHandler.getExpressionParser() .parseExpression(this.expression.getExpressionString()); } /** * Determines the access by evaluating the provided expression. * @param authentication the {@link Supplier} of the {@link Authentication} to check * @param context the {@link RequestAuthorizationContext} to check * @return an {@link ExpressionAuthorizationDecision} based on the evaluated * expression */ @Override public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) { EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication, context); boolean granted = ExpressionUtils.evaluateAsBoolean(this.expression, ctx); return new ExpressionAuthorizationDecision(granted, this.expression); } @Override public String toString() { return "WebExpressionAuthorizationManager[expression='" + this.expression + "']"; } }
3,578
40.616279
127
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSource.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.access.expression; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.BiConsumer; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.expression.ExpressionParser; import org.springframework.expression.ParseException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Expression-based {@code FilterInvocationSecurityMetadataSource}. * * @author Luke Taylor * @author Eddú Meléndez * @since 3.0 */ public final class ExpressionBasedFilterInvocationSecurityMetadataSource extends DefaultFilterInvocationSecurityMetadataSource { private static final Log logger = LogFactory.getLog(ExpressionBasedFilterInvocationSecurityMetadataSource.class); public ExpressionBasedFilterInvocationSecurityMetadataSource( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap, SecurityExpressionHandler<FilterInvocation> expressionHandler) { super(processMap(requestMap, expressionHandler.getExpressionParser())); Assert.notNull(expressionHandler, "A non-null SecurityExpressionHandler is required"); } private static LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processMap( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap, ExpressionParser parser) { Assert.notNull(parser, "SecurityExpressionHandler returned a null parser object"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processed = new LinkedHashMap<>(requestMap); requestMap.forEach((request, value) -> process(parser, request, value, processed::put)); return processed; } private static void process(ExpressionParser parser, RequestMatcher request, Collection<ConfigAttribute> value, BiConsumer<RequestMatcher, Collection<ConfigAttribute>> consumer) { String expression = getExpression(request, value); if (logger.isDebugEnabled()) { logger.debug(LogMessage.format("Adding web access control expression [%s] for %s", expression, request)); } AbstractVariableEvaluationContextPostProcessor postProcessor = createPostProcessor(request); ArrayList<ConfigAttribute> processed = new ArrayList<>(1); try { processed.add(new WebExpressionConfigAttribute(parser.parseExpression(expression), postProcessor)); } catch (ParseException ex) { throw new IllegalArgumentException("Failed to parse expression '" + expression + "'"); } consumer.accept(request, processed); } private static String getExpression(RequestMatcher request, Collection<ConfigAttribute> value) { Assert.isTrue(value.size() == 1, () -> "Expected a single expression attribute for " + request); return value.toArray(new ConfigAttribute[1])[0].getAttribute(); } private static AbstractVariableEvaluationContextPostProcessor createPostProcessor(RequestMatcher request) { return new RequestVariablesExtractorEvaluationContextPostProcessor(request); } static class AntPathMatcherEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor { private final AntPathRequestMatcher matcher; AntPathMatcherEvaluationContextPostProcessor(AntPathRequestMatcher matcher) { this.matcher = matcher; } @Override Map<String, String> extractVariables(HttpServletRequest request) { return this.matcher.matcher(request).getVariables(); } } static class RequestVariablesExtractorEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor { private final RequestMatcher matcher; RequestVariablesExtractorEvaluationContextPostProcessor(RequestMatcher matcher) { this.matcher = matcher; } @Override Map<String, String> extractVariables(HttpServletRequest request) { return this.matcher.matcher(request).getVariables(); } } }
5,009
39.08
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandler.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.expression; import org.springframework.security.access.expression.AbstractSecurityExpressionHandler; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.access.expression.SecurityExpressionOperations; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; /** * @author Luke Taylor * @author Eddú Meléndez * @since 3.0 */ public class DefaultWebSecurityExpressionHandler extends AbstractSecurityExpressionHandler<FilterInvocation> implements SecurityExpressionHandler<FilterInvocation> { private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); private String defaultRolePrefix = "ROLE_"; @Override protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) { WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(authentication, fi); root.setPermissionEvaluator(getPermissionEvaluator()); root.setTrustResolver(this.trustResolver); root.setRoleHierarchy(getRoleHierarchy()); root.setDefaultRolePrefix(this.defaultRolePrefix); return root; } /** * Sets the {@link AuthenticationTrustResolver} to be used. The default is * {@link AuthenticationTrustResolverImpl}. * @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be * null. */ public void setTrustResolver(AuthenticationTrustResolver trustResolver) { Assert.notNull(trustResolver, "trustResolver cannot be null"); this.trustResolver = trustResolver; } /** * <p> * Sets the default prefix to be added to * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)} * or * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}. * For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the * role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default). * </p> * * <p> * If null or empty, then no default role prefix is used. * </p> * @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_". */ public void setDefaultRolePrefix(String defaultRolePrefix) { this.defaultRolePrefix = defaultRolePrefix; } }
3,207
38.121951
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionConfigAttribute.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.expression; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; /** * Simple expression configuration attribute for use in web request authorizations. * * @author Luke Taylor * @since 3.0 */ class WebExpressionConfigAttribute implements ConfigAttribute, EvaluationContextPostProcessor<FilterInvocation> { private final Expression authorizeExpression; private final EvaluationContextPostProcessor<FilterInvocation> postProcessor; WebExpressionConfigAttribute(Expression authorizeExpression, EvaluationContextPostProcessor<FilterInvocation> postProcessor) { this.authorizeExpression = authorizeExpression; this.postProcessor = postProcessor; } Expression getAuthorizeExpression() { return this.authorizeExpression; } @Override public EvaluationContext postProcess(EvaluationContext context, FilterInvocation fi) { return (this.postProcessor != null) ? this.postProcessor.postProcess(context, fi) : context; } @Override public String getAttribute() { return null; } @Override public String toString() { return this.authorizeExpression.getExpressionString(); } }
1,948
30.435484
113
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/EvaluationContextPostProcessor.java
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.expression; import org.springframework.expression.EvaluationContext; /** * * /** Allows post processing the {@link EvaluationContext} * * <p> * This API is intentionally kept package scope as it may evolve over time. * </p> * * @param <I> the invocation to use for post processing * @author Rob Winch * @since 4.1 */ interface EvaluationContextPostProcessor<I> { /** * Allows post processing of the {@link EvaluationContext}. Implementations may return * a new instance of {@link EvaluationContext} or modify the {@link EvaluationContext} * that was passed in. * @param context the original {@link EvaluationContext} * @param invocation the security invocation object (i.e. FilterInvocation) * @return the upated context. */ EvaluationContext postProcess(EvaluationContext context, I invocation); }
1,501
31.652174
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/expression/DelegatingEvaluationContext.java
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.expression; import java.util.List; import org.springframework.expression.BeanResolver; import org.springframework.expression.ConstructorResolver; import org.springframework.expression.EvaluationContext; import org.springframework.expression.MethodResolver; import org.springframework.expression.OperatorOverloader; import org.springframework.expression.PropertyAccessor; import org.springframework.expression.TypeComparator; import org.springframework.expression.TypeConverter; import org.springframework.expression.TypeLocator; import org.springframework.expression.TypedValue; /** * An instance of {@link EvaluationContext} that delegates to another implementation. * * @author Rob Winch * @since 4.1 */ class DelegatingEvaluationContext implements EvaluationContext { private final EvaluationContext delegate; DelegatingEvaluationContext(EvaluationContext delegate) { this.delegate = delegate; } @Override public TypedValue getRootObject() { return this.delegate.getRootObject(); } @Override public List<ConstructorResolver> getConstructorResolvers() { return this.delegate.getConstructorResolvers(); } @Override public List<MethodResolver> getMethodResolvers() { return this.delegate.getMethodResolvers(); } @Override public List<PropertyAccessor> getPropertyAccessors() { return this.delegate.getPropertyAccessors(); } @Override public TypeLocator getTypeLocator() { return this.delegate.getTypeLocator(); } @Override public TypeConverter getTypeConverter() { return this.delegate.getTypeConverter(); } @Override public TypeComparator getTypeComparator() { return this.delegate.getTypeComparator(); } @Override public OperatorOverloader getOperatorOverloader() { return this.delegate.getOperatorOverloader(); } @Override public BeanResolver getBeanResolver() { return this.delegate.getBeanResolver(); } @Override public void setVariable(String name, Object value) { this.delegate.setVariable(name, value); } @Override public Object lookupVariable(String name) { return this.delegate.lookupVariable(name); } }
2,767
26.137255
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Classes that ensure web requests are received over required transport channels. * <p> * Most commonly used to enforce that requests are submitted over HTTP or HTTPS. */ package org.springframework.security.web.access.channel;
859
36.391304
82
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; /** * Implementation of {@link ChannelDecisionManager}. * <p> * Iterates through each configured {@link ChannelProcessor}. If a * <code>ChannelProcessor</code> has any issue with the security of the request, it should * cause a redirect, exception or whatever other action is appropriate for the * <code>ChannelProcessor</code> implementation. * <p> * Once any response is committed (ie a redirect is written to the response object), the * <code>ChannelDecisionManagerImpl</code> will not iterate through any further * <code>ChannelProcessor</code>s. * <p> * The attribute "ANY_CHANNEL" if applied to a particular URL, the iteration through the * channel processors will be skipped (see SEC-494, SEC-335). * * @author Ben Alex */ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, InitializingBean { public static final String ANY_CHANNEL = "ANY_CHANNEL"; private List<ChannelProcessor> channelProcessors; @Override public void afterPropertiesSet() { Assert.notEmpty(this.channelProcessors, "A list of ChannelProcessors is required"); } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { for (ConfigAttribute attribute : config) { if (ANY_CHANNEL.equals(attribute.getAttribute())) { return; } } for (ChannelProcessor processor : this.channelProcessors) { processor.decide(invocation, config); if (invocation.getResponse().isCommitted()) { break; } } } protected List<ChannelProcessor> getChannelProcessors() { return this.channelProcessors; } @SuppressWarnings("cast") public void setChannelProcessors(List<?> channelProcessors) { Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required"); this.channelProcessors = new ArrayList<>(channelProcessors.size()); for (Object currentObject : channelProcessors) { Assert.isInstanceOf(ChannelProcessor.class, currentObject, () -> "ChannelProcessor " + currentObject.getClass().getName() + " must implement ChannelProcessor"); this.channelProcessors.add((ChannelProcessor) currentObject); } } @Override public boolean supports(ConfigAttribute attribute) { if (ANY_CHANNEL.equals(attribute.getAttribute())) { return true; } for (ChannelProcessor processor : this.channelProcessors) { if (processor.supports(attribute)) { return true; } } return false; } }
3,496
32.625
93
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/SecureChannelProcessor.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.Collection; import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; /** * Ensures channel security is active by review of * <code>HttpServletRequest.isSecure()</code> responses. * <p> * The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this * keyword is detected, <code>HttpServletRequest.isSecure()</code> is used to determine * the channel security offered. If channel security is not present, the configured * <code>ChannelEntryPoint</code> is called. By default the entry point is * {@link RetryWithHttpsEntryPoint}. * <p> * The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>. * * @author Ben Alex */ public class SecureChannelProcessor implements InitializingBean, ChannelProcessor { private ChannelEntryPoint entryPoint = new RetryWithHttpsEntryPoint(); private String secureKeyword = "REQUIRES_SECURE_CHANNEL"; @Override public void afterPropertiesSet() { Assert.hasLength(this.secureKeyword, "secureKeyword required"); Assert.notNull(this.entryPoint, "entryPoint required"); } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (!invocation.getHttpRequest().isSecure()) { this.entryPoint.commence(invocation.getRequest(), invocation.getResponse()); } } } } public ChannelEntryPoint getEntryPoint() { return this.entryPoint; } public String getSecureKeyword() { return this.secureKeyword; } public void setEntryPoint(ChannelEntryPoint entryPoint) { this.entryPoint = entryPoint; } public void setSecureKeyword(String secureKeyword) { this.secureKeyword = secureKeyword; } @Override public boolean supports(ConfigAttribute attribute) { return (attribute != null) && (attribute.getAttribute() != null) && attribute.getAttribute().equals(getSecureKeyword()); } }
2,988
31.846154
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPoint.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; /** * Commences a secure channel by retrying the original request using HTTPS. * <p> * This entry point should suffice in most circumstances. However, it is not intended to * properly handle HTTP POSTs or other usage where a standard redirect would cause an * issue. * </p> * * @author Ben Alex */ public class RetryWithHttpsEntryPoint extends AbstractRetryEntryPoint { public RetryWithHttpsEntryPoint() { super("https://", 443); } @Override protected Integer getMappedPort(Integer mapFromPort) { return getPortMapper().lookupHttpsPort(mapFromPort); } }
1,260
29.756098
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/InsecureChannelProcessor.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.Collection; import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.util.Assert; /** * Ensures channel security is inactive by review of * <code>HttpServletRequest.isSecure()</code> responses. * <p> * The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this * keyword is detected, <code>HttpServletRequest.isSecure()</code> is used to determine * the channel security offered. If channel security is present, the configured * <code>ChannelEntryPoint</code> is called. By default the entry point is * {@link RetryWithHttpEntryPoint}. * <p> * The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>. * * @author Ben Alex */ public class InsecureChannelProcessor implements InitializingBean, ChannelProcessor { private ChannelEntryPoint entryPoint = new RetryWithHttpEntryPoint(); private String insecureKeyword = "REQUIRES_INSECURE_CHANNEL"; @Override public void afterPropertiesSet() { Assert.hasLength(this.insecureKeyword, "insecureKeyword required"); Assert.notNull(this.entryPoint, "entryPoint required"); } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue(invocation != null && config != null, "Nulls cannot be provided"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (invocation.getHttpRequest().isSecure()) { this.entryPoint.commence(invocation.getRequest(), invocation.getResponse()); } } } } public ChannelEntryPoint getEntryPoint() { return this.entryPoint; } public String getInsecureKeyword() { return this.insecureKeyword; } public void setEntryPoint(ChannelEntryPoint entryPoint) { this.entryPoint = entryPoint; } public void setInsecureKeyword(String secureKeyword) { this.insecureKeyword = secureKeyword; } @Override public boolean supports(ConfigAttribute attribute) { return (attribute != null) && (attribute.getAttribute() != null) && attribute.getAttribute().equals(getInsecureKeyword()); } }
3,005
32.032967
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.PortMapper; import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.PortResolver; import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.RedirectStrategy; import org.springframework.util.Assert; /** * @author Luke Taylor */ public abstract class AbstractRetryEntryPoint implements ChannelEntryPoint { protected final Log logger = LogFactory.getLog(getClass()); private PortMapper portMapper = new PortMapperImpl(); private PortResolver portResolver = new PortResolverImpl(); /** * The scheme ("http://" or "https://") */ private final String scheme; /** * The standard port for the scheme (80 for http, 443 for https) */ private final int standardPort; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); public AbstractRetryEntryPoint(String scheme, int standardPort) { this.scheme = scheme; this.standardPort = standardPort; } @Override public void commence(HttpServletRequest request, HttpServletResponse response) throws IOException { String queryString = request.getQueryString(); String redirectUrl = request.getRequestURI() + ((queryString != null) ? ("?" + queryString) : ""); Integer currentPort = this.portResolver.getServerPort(request); Integer redirectPort = getMappedPort(currentPort); if (redirectPort != null) { boolean includePort = redirectPort != this.standardPort; String port = (includePort) ? (":" + redirectPort) : ""; redirectUrl = this.scheme + request.getServerName() + port + redirectUrl; } this.logger.debug(LogMessage.format("Redirecting to: %s", redirectUrl)); this.redirectStrategy.sendRedirect(request, response, redirectUrl); } protected abstract Integer getMappedPort(Integer mapFromPort); protected final PortMapper getPortMapper() { return this.portMapper; } public void setPortMapper(PortMapper portMapper) { Assert.notNull(portMapper, "portMapper cannot be null"); this.portMapper = portMapper; } public void setPortResolver(PortResolver portResolver) { Assert.notNull(portResolver, "portResolver cannot be null"); this.portResolver = portResolver; } protected final PortResolver getPortResolver() { return this.portResolver; } /** * Sets the strategy to be used for redirecting to the required channel URL. A * {@code DefaultRedirectStrategy} instance will be used if not set. * @param redirectStrategy the strategy instance to which the URL will be passed. */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } protected final RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } }
3,834
32.938053
100
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPoint.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; /** * Commences an insecure channel by retrying the original request using HTTP. * <p> * This entry point should suffice in most circumstances. However, it is not intended to * properly handle HTTP POSTs or other usage where a standard redirect would cause an * issue. * * @author Ben Alex */ public class RetryWithHttpEntryPoint extends AbstractRetryEntryPoint { public RetryWithHttpEntryPoint() { super("http://", 80); } @Override protected Integer getMappedPort(Integer mapFromPort) { return getPortMapper().lookupHttpPort(mapFromPort); } }
1,249
30.25
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManager.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.Collection; import jakarta.servlet.ServletException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; /** * Decides whether a web channel provides sufficient security. * * @author Ben Alex */ public interface ChannelDecisionManager { /** * Decided whether the presented {@link FilterInvocation} provides the appropriate * level of channel security based on the requested list of <tt>ConfigAttribute</tt>s. * */ void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException; /** * Indicates whether this <code>ChannelDecisionManager</code> is able to process the * passed <code>ConfigAttribute</code>. * <p> * This allows the <code>ChannelProcessingFilter</code> to check every configuration * attribute can be consumed by the configured <code>ChannelDecisionManager</code>. * </p> * @param attribute a configuration attribute that has been configured against the * <code>ChannelProcessingFilter</code> * @return true if this <code>ChannelDecisionManager</code> can support the passed * configuration attribute */ boolean supports(ConfigAttribute attribute); }
1,955
33.928571
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/ChannelEntryPoint.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * May be used by a {@link ChannelProcessor} to launch a web channel. * * <p> * <code>ChannelProcessor</code>s can elect to launch a new web channel directly, or they * can delegate to another class. The <code>ChannelEntryPoint</code> is a pluggable * interface to assist <code>ChannelProcessor</code>s in performing this delegation. * * @author Ben Alex */ public interface ChannelEntryPoint { /** * Commences a secure channel. * <p> * Implementations should modify the headers on the <code>ServletResponse</code> as * necessary to commence the user agent using the implementation's supported channel * type. * @param request that a <code>ChannelProcessor</code> has rejected * @param response so that the user agent can begin using a new channel * */ void commence(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; }
1,752
34.06
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * Ensures a web request is delivered over the required channel. * <p> * Internally uses a {@link FilterInvocation} to represent the request, allowing a * {@code FilterInvocationSecurityMetadataSource} to be used to lookup the attributes * which apply. * <p> * Delegates the actual channel security decisions and necessary actions to the configured * {@link ChannelDecisionManager}. If a response is committed by the * {@code ChannelDecisionManager}, the filter chain will not proceed. * <p> * The most common usage is to ensure that a request takes place over HTTPS, where the * {@link ChannelDecisionManagerImpl} is configured with a {@link SecureChannelProcessor} * and an {@link InsecureChannelProcessor}. A typical configuration would be * * <pre> * * &lt;bean id="channelProcessingFilter" class="org.springframework.security.web.access.channel.ChannelProcessingFilter"&gt; * &lt;property name="channelDecisionManager" ref="channelDecisionManager"/&gt; * &lt;property name="securityMetadataSource"&gt; * &lt;security:filter-security-metadata-source request-matcher="regex"&gt; * &lt;security:intercept-url pattern="\A/secure/.*\Z" access="REQUIRES_SECURE_CHANNEL"/&gt; * &lt;security:intercept-url pattern="\A/login.jsp.*\Z" access="REQUIRES_SECURE_CHANNEL"/&gt; * &lt;security:intercept-url pattern="\A/.*\Z" access="ANY_CHANNEL"/&gt; * &lt;/security:filter-security-metadata-source&gt; * &lt;/property&gt; * &lt;/bean&gt; * * &lt;bean id="channelDecisionManager" class="org.springframework.security.web.access.channel.ChannelDecisionManagerImpl"&gt; * &lt;property name="channelProcessors"&gt; * &lt;list&gt; * &lt;ref bean="secureChannelProcessor"/&gt; * &lt;ref bean="insecureChannelProcessor"/&gt; * &lt;/list&gt; * &lt;/property&gt; * &lt;/bean&gt; * * &lt;bean id="secureChannelProcessor" * class="org.springframework.security.web.access.channel.SecureChannelProcessor"/&gt; * &lt;bean id="insecureChannelProcessor" * class="org.springframework.security.web.access.channel.InsecureChannelProcessor"/&gt; * * </pre> * * which would force the login form and any access to the {@code /secure} path to be made * over HTTPS. * * @author Ben Alex */ public class ChannelProcessingFilter extends GenericFilterBean { private ChannelDecisionManager channelDecisionManager; private FilterInvocationSecurityMetadataSource securityMetadataSource; @Override public void afterPropertiesSet() { Assert.notNull(this.securityMetadataSource, "securityMetadataSource must be specified"); Assert.notNull(this.channelDecisionManager, "channelDecisionManager must be specified"); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAllConfigAttributes(); if (attributes == null) { this.logger.warn("Could not validate configuration attributes as the " + "FilterInvocationSecurityMetadataSource did not return any attributes"); return; } Set<ConfigAttribute> unsupportedAttributes = getUnsupportedAttributes(attributes); Assert.isTrue(unsupportedAttributes.isEmpty(), () -> "Unsupported configuration attributes: " + unsupportedAttributes); this.logger.info("Validated configuration attributes"); } private Set<ConfigAttribute> getUnsupportedAttributes(Collection<ConfigAttribute> attrDefs) { Set<ConfigAttribute> unsupportedAttributes = new HashSet<>(); for (ConfigAttribute attr : attrDefs) { if (!this.channelDecisionManager.supports(attr)) { unsupportedAttributes.add(attr); } } return unsupportedAttributes; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; FilterInvocation filterInvocation = new FilterInvocation(request, response, chain); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(filterInvocation); if (attributes != null) { this.logger.debug(LogMessage.format("Request: %s; ConfigAttributes: %s", filterInvocation, attributes)); this.channelDecisionManager.decide(filterInvocation, attributes); if (filterInvocation.getResponse().isCommitted()) { return; } } chain.doFilter(request, response); } protected ChannelDecisionManager getChannelDecisionManager() { return this.channelDecisionManager; } protected FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager) { this.channelDecisionManager = channelDecisionManager; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) { this.securityMetadataSource = filterInvocationSecurityMetadataSource; } }
6,340
40.175325
126
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessor.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.channel; import java.io.IOException; import java.util.Collection; import jakarta.servlet.ServletException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; /** * Decides whether a web channel meets a specific security condition. * <p> * <code>ChannelProcessor</code> implementations are iterated by the * {@link ChannelDecisionManagerImpl}. * <p> * If an implementation has an issue with the channel security, they should take action * themselves. The callers of the implementation do not take any action. * * @author Ben Alex */ public interface ChannelProcessor { /** * Decided whether the presented {@link FilterInvocation} provides the appropriate * level of channel security based on the requested list of <tt>ConfigAttribute</tt>s. */ void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException; /** * Indicates whether this <code>ChannelProcessor</code> is able to process the passed * <code>ConfigAttribute</code>. * <p> * This allows the <code>ChannelProcessingFilter</code> to check every configuration * attribute can be consumed by the configured <code>ChannelDecisionManager</code>. * @param attribute a configuration attribute that has been configured against the * <tt>ChannelProcessingFilter</tt>. * @return true if this <code>ChannelProcessor</code> can support the passed * configuration attribute */ boolean supports(ConfigAttribute attribute); }
2,211
35.866667
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Enforcement of security for HTTP requests, typically by the URL requested. */ package org.springframework.security.web.access.intercept;
768
35.619048
77
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSource.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.intercept; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.RequestMatcher; /** * Default implementation of <tt>FilterInvocationDefinitionSource</tt>. * <p> * Stores an ordered map of {@link RequestMatcher}s to <tt>ConfigAttribute</tt> * collections and provides matching of {@code FilterInvocation}s against the items stored * in the map. * <p> * The order of the {@link RequestMatcher}s in the map is very important. The <b>first</b> * one which matches the request will be used. Later matchers in the map will not be * invoked if a match has already been found. Accordingly, the most specific matchers * should be registered first, with the most general matches registered last. * <p> * The most common method creating an instance is using the Spring Security namespace. For * example, the {@code pattern} and {@code access} attributes of the * {@code <intercept-url>} elements defined as children of the {@code <http>} element are * combined to build the instance used by the {@code FilterSecurityInterceptor}. * * @author Ben Alex * @author Luke Taylor */ public class DefaultFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { protected final Log logger = LogFactory.getLog(getClass()); private final Map<RequestMatcher, Collection<ConfigAttribute>> requestMap; /** * Sets the internal request map from the supplied map. The key elements should be of * type {@link RequestMatcher}, which. The path stored in the key will depend on the * type of the supplied UrlMatcher. * @param requestMap order-preserving map of request definitions to attribute lists */ public DefaultFilterInvocationSecurityMetadataSource( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap) { this.requestMap = requestMap; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { Set<ConfigAttribute> allAttributes = new HashSet<>(); this.requestMap.values().forEach(allAttributes::addAll); return allAttributes; } @Override public Collection<ConfigAttribute> getAttributes(Object object) { final HttpServletRequest request = ((FilterInvocation) object).getRequest(); int count = 0; for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : this.requestMap.entrySet()) { if (entry.getKey().matches(request)) { return entry.getValue(); } else { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Did not match request to %s - %s (%d/%d)", entry.getKey(), entry.getValue(), ++count, this.requestMap.size())); } } } return null; } @Override public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } }
3,845
36.705882
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/RequestAuthorizationContext.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.access.intercept; import java.util.Collections; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; /** * An {@link HttpServletRequest} authorization context. * * @author Evgeniy Cheban * @since 5.5 */ public final class RequestAuthorizationContext { private final HttpServletRequest request; private final Map<String, String> variables; /** * Creates an instance. * @param request the {@link HttpServletRequest} to use */ public RequestAuthorizationContext(HttpServletRequest request) { this(request, Collections.emptyMap()); } /** * Creates an instance. * @param request the {@link HttpServletRequest} to use * @param variables a map containing key-value pairs representing extracted variable * names and variable values */ public RequestAuthorizationContext(HttpServletRequest request, Map<String, String> variables) { this.request = request; this.variables = variables; } /** * Returns the {@link HttpServletRequest}. * @return the {@link HttpServletRequest} to use */ public HttpServletRequest getRequest() { return this.request; } /** * Returns the extracted variable values where the key is the variable name and the * value is the variable value. * @return a map containing key-value pairs representing extracted variable names and * variable values */ public Map<String, String> getVariables() { return this.variables; } }
2,085
27.189189
96
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManager.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.access.intercept; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.authorization.AuthenticatedAuthorizationManager; import org.springframework.security.authorization.AuthorityAuthorizationManager; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult; import org.springframework.security.web.util.matcher.RequestMatcherEntry; import org.springframework.util.Assert; /** * An {@link AuthorizationManager} which delegates to a specific * {@link AuthorizationManager} based on a {@link RequestMatcher} evaluation. * * @author Evgeniy Cheban * @author Parikshit Dutta * @since 5.5 */ public final class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { private static final AuthorizationDecision DENY = new AuthorizationDecision(false); private final Log logger = LogFactory.getLog(getClass()); private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings; private RequestMatcherDelegatingAuthorizationManager( List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings) { Assert.notEmpty(mappings, "mappings cannot be empty"); this.mappings = mappings; } /** * Delegates to a specific {@link AuthorizationManager} based on a * {@link RequestMatcher} evaluation. * @param authentication the {@link Supplier} of the {@link Authentication} to check * @param request the {@link HttpServletRequest} to check * @return an {@link AuthorizationDecision}. If there is no {@link RequestMatcher} * matching the request, or the {@link AuthorizationManager} could not decide, then * null is returned */ @Override public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Authorizing %s", request)); } for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) { RequestMatcher matcher = mapping.getRequestMatcher(); MatchResult matchResult = matcher.matcher(request); if (matchResult.isMatch()) { AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry(); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Checking authorization on %s using %s", request, manager)); } return manager.check(authentication, new RequestAuthorizationContext(request, matchResult.getVariables())); } } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Denying request since did not find matching RequestMatcher")); } return DENY; } /** * Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}. * @return the new {@link Builder} instance */ public static Builder builder() { return new Builder(); } /** * A builder for {@link RequestMatcherDelegatingAuthorizationManager}. */ public static final class Builder { private boolean anyRequestConfigured; private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings = new ArrayList<>(); /** * Maps a {@link RequestMatcher} to an {@link AuthorizationManager}. * @param matcher the {@link RequestMatcher} to use * @param manager the {@link AuthorizationManager} to use * @return the {@link Builder} for further customizations */ public Builder add(RequestMatcher matcher, AuthorizationManager<RequestAuthorizationContext> manager) { Assert.state(!this.anyRequestConfigured, "Can't add mappings after anyRequest"); Assert.notNull(matcher, "matcher cannot be null"); Assert.notNull(manager, "manager cannot be null"); this.mappings.add(new RequestMatcherEntry<>(matcher, manager)); return this; } /** * Allows to configure the {@link RequestMatcher} to {@link AuthorizationManager} * mappings. * @param mappingsConsumer used to configure the {@link RequestMatcher} to * {@link AuthorizationManager} mappings. * @return the {@link Builder} for further customizations * @since 5.7 */ public Builder mappings( Consumer<List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>>> mappingsConsumer) { Assert.state(!this.anyRequestConfigured, "Can't configure mappings after anyRequest"); Assert.notNull(mappingsConsumer, "mappingsConsumer cannot be null"); mappingsConsumer.accept(this.mappings); return this; } /** * Maps any request. * @return the {@link AuthorizedUrl} for further customizations * @since 6.2 */ public AuthorizedUrl anyRequest() { Assert.state(!this.anyRequestConfigured, "Can't configure anyRequest after itself"); this.anyRequestConfigured = true; return new AuthorizedUrl(AnyRequestMatcher.INSTANCE); } /** * Maps {@link RequestMatcher}s to {@link AuthorizationManager}. * @param matchers the {@link RequestMatcher}s to map * @return the {@link AuthorizedUrl} for further customizations * @since 6.2 */ public AuthorizedUrl requestMatchers(RequestMatcher... matchers) { Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); return new AuthorizedUrl(matchers); } /** * Creates a {@link RequestMatcherDelegatingAuthorizationManager} instance. * @return the {@link RequestMatcherDelegatingAuthorizationManager} instance */ public RequestMatcherDelegatingAuthorizationManager build() { return new RequestMatcherDelegatingAuthorizationManager(this.mappings); } /** * An object that allows configuring the {@link AuthorizationManager} for * {@link RequestMatcher}s. * * @author Evgeniy Cheban * @since 6.2 */ public final class AuthorizedUrl { private final List<RequestMatcher> matchers; private AuthorizedUrl(RequestMatcher... matchers) { this(List.of(matchers)); } private AuthorizedUrl(List<RequestMatcher> matchers) { this.matchers = matchers; } /** * Specify that URLs are allowed by anyone. * @return the {@link Builder} for further customizations */ public Builder permitAll() { return access((a, o) -> new AuthorizationDecision(true)); } /** * Specify that URLs are not allowed by anyone. * @return the {@link Builder} for further customizations */ public Builder denyAll() { return access((a, o) -> new AuthorizationDecision(false)); } /** * Specify that URLs are allowed by any authenticated user. * @return the {@link Builder} for further customizations */ public Builder authenticated() { return access(AuthenticatedAuthorizationManager.authenticated()); } /** * Specify that URLs are allowed by users who have authenticated and were not * "remembered". * @return the {@link Builder} for further customization */ public Builder fullyAuthenticated() { return access(AuthenticatedAuthorizationManager.fullyAuthenticated()); } /** * Specify that URLs are allowed by users that have been remembered. * @return the {@link Builder} for further customization */ public Builder rememberMe() { return access(AuthenticatedAuthorizationManager.rememberMe()); } /** * Specify that URLs are allowed by anonymous users. * @return the {@link Builder} for further customization */ public Builder anonymous() { return access(AuthenticatedAuthorizationManager.anonymous()); } /** * Specifies a user requires a role. * @param role the role that should be required which is prepended with ROLE_ * automatically (i.e. USER, ADMIN, etc). It should not start with ROLE_ * @return {@link Builder} for further customizations */ public Builder hasRole(String role) { return access(AuthorityAuthorizationManager.hasRole(role)); } /** * Specifies that a user requires one of many roles. * @param roles the roles that the user should have at least one of (i.e. * ADMIN, USER, etc). Each role should not start with ROLE_ since it is * automatically prepended already * @return the {@link Builder} for further customizations */ public Builder hasAnyRole(String... roles) { return access(AuthorityAuthorizationManager.hasAnyRole(roles)); } /** * Specifies a user requires an authority. * @param authority the authority that should be required * @return the {@link Builder} for further customizations */ public Builder hasAuthority(String authority) { return access(AuthorityAuthorizationManager.hasAuthority(authority)); } /** * Specifies that a user requires one of many authorities. * @param authorities the authorities that the user should have at least one * of (i.e. ROLE_USER, ROLE_ADMIN, etc) * @return the {@link Builder} for further customizations */ public Builder hasAnyAuthority(String... authorities) { return access(AuthorityAuthorizationManager.hasAnyAuthority(authorities)); } private Builder access(AuthorizationManager<RequestAuthorizationContext> manager) { for (RequestMatcher matcher : this.matchers) { Builder.this.mappings.add(new RequestMatcherEntry<>(matcher, manager)); } return Builder.this; } } } }
10,574
35.215753
122
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.intercept; import java.io.IOException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.web.FilterInvocation; /** * Performs security handling of HTTP resources via a filter implementation. * <p> * The <code>SecurityMetadataSource</code> required by this security interceptor is of * type {@link FilterInvocationSecurityMetadataSource}. * <p> * Refer to {@link AbstractSecurityInterceptor} for details on the workflow. * </p> * * @author Ben Alex * @author Rob Winch * @deprecated Use {@link AuthorizationFilter} instead */ @Deprecated public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { private static final String FILTER_APPLIED = "__spring_security_filterSecurityInterceptor_filterApplied"; private FilterInvocationSecurityMetadataSource securityMetadataSource; private boolean observeOncePerRequest = false; /** * Not used (we rely on IoC container lifecycle services instead) * @param arg0 ignored * */ @Override public void init(FilterConfig arg0) { } /** * Not used (we rely on IoC container lifecycle services instead) */ @Override public void destroy() { } /** * Method that is actually called by the filter chain. Simply delegates to the * {@link #invoke(FilterInvocation)} method. * @param request the servlet request * @param response the servlet response * @param chain the filter chain * @throws IOException if the filter chain fails * @throws ServletException if the filter chain fails */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { invoke(new FilterInvocation(request, response, chain)); } public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } public void invoke(FilterInvocation filterInvocation) throws IOException, ServletException { if (isApplied(filterInvocation) && this.observeOncePerRequest) { // filter already applied to this request and user wants us to observe // once-per-request handling, so don't re-do security checking filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse()); return; } // first time this request being called, so perform security checking if (filterInvocation.getRequest() != null && this.observeOncePerRequest) { filterInvocation.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(filterInvocation); try { filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } private boolean isApplied(FilterInvocation filterInvocation) { return (filterInvocation.getRequest() != null) && (filterInvocation.getRequest().getAttribute(FILTER_APPLIED) != null); } /** * Indicates whether once-per-request handling will be observed. By default this is * <code>true</code>, meaning the <code>FilterSecurityInterceptor</code> will only * execute once-per-request. Sometimes users may wish it to execute more than once per * request, such as when JSP forwards are being used and filter security is desired on * each included fragment of the HTTP request. * @return <code>true</code> (the default) if once-per-request is honoured, otherwise * <code>false</code> if <code>FilterSecurityInterceptor</code> will enforce * authorizations for each and every fragment of the HTTP request. */ public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } }
5,271
34.38255
106
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/RequestKey.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.access.intercept; import org.springframework.util.Assert; /** * @author Luke Taylor * @since 2.0 */ public class RequestKey { private final String url; private final String method; public RequestKey(String url) { this(url, null); } public RequestKey(String url, String method) { Assert.notNull(url, "url cannot be null"); this.url = url; this.method = method; } String getUrl() { return this.url; } String getMethod() { return this.method; } @Override public boolean equals(Object obj) { if (!(obj instanceof RequestKey key)) { return false; } if (!this.url.equals(key.url)) { return false; } if (this.method == null) { return key.method == null; } return this.method.equals(key.method); } @Override public int hashCode() { int result = this.url.hashCode(); result = 31 * result + ((this.method != null) ? this.method.hashCode() : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(this.url.length() + 7); sb.append("["); if (this.method != null) { sb.append(this.method).append(","); } sb.append(this.url); sb.append("]"); return sb.toString(); } }
1,850
21.301205
78
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/FilterInvocationSecurityMetadataSource.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.access.intercept; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.web.FilterInvocation; /** * Marker interface for <code>SecurityMetadataSource</code> implementations that are * designed to perform lookups keyed on {@link FilterInvocation}s. * * @author Ben Alex */ public interface FilterInvocationSecurityMetadataSource extends SecurityMetadataSource { }
1,088
34.129032
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/access/intercept/AuthorizationFilter.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.access.intercept; import java.io.IOException; import java.util.function.Supplier; import jakarta.servlet.DispatcherType; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationEventPublisher; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.authorization.event.AuthorizationDeniedEvent; import org.springframework.security.authorization.event.AuthorizationGrantedEvent; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * An authorization filter that restricts access to the URL using * {@link AuthorizationManager}. * * @author Evgeniy Cheban * @since 5.5 */ public class AuthorizationFilter extends GenericFilterBean { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private final AuthorizationManager<HttpServletRequest> authorizationManager; private AuthorizationEventPublisher eventPublisher = AuthorizationFilter::noPublish; private boolean observeOncePerRequest = false; private boolean filterErrorDispatch = true; private boolean filterAsyncDispatch = true; /** * Creates an instance. * @param authorizationManager the {@link AuthorizationManager} to use */ public AuthorizationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) { Assert.notNull(authorizationManager, "authorizationManager cannot be null"); this.authorizationManager = authorizationManager; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (this.observeOncePerRequest && isApplied(request)) { chain.doFilter(request, response); return; } if (skipDispatch(request)) { chain.doFilter(request, response); return; } String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName(); request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE); try { AuthorizationDecision decision = this.authorizationManager.check(this::getAuthentication, request); this.eventPublisher.publishAuthorizationEvent(this::getAuthentication, request, decision); if (decision != null && !decision.isGranted()) { throw new AccessDeniedException("Access Denied"); } chain.doFilter(request, response); } finally { request.removeAttribute(alreadyFilteredAttributeName); } } private boolean skipDispatch(HttpServletRequest request) { if (DispatcherType.ERROR.equals(request.getDispatcherType()) && !this.filterErrorDispatch) { return true; } if (DispatcherType.ASYNC.equals(request.getDispatcherType()) && !this.filterAsyncDispatch) { return true; } return false; } private boolean isApplied(HttpServletRequest request) { return request.getAttribute(getAlreadyFilteredAttributeName()) != null; } private String getAlreadyFilteredAttributeName() { String name = getFilterName(); if (name == null) { name = getClass().getName(); } return name + ".APPLIED"; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } private Authentication getAuthentication() { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; } /** * Use this {@link AuthorizationEventPublisher} to publish * {@link AuthorizationDeniedEvent}s and {@link AuthorizationGrantedEvent}s. * @param eventPublisher the {@link ApplicationEventPublisher} to use * @since 5.7 */ public void setAuthorizationEventPublisher(AuthorizationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "eventPublisher cannot be null"); this.eventPublisher = eventPublisher; } /** * Gets the {@link AuthorizationManager} used by this filter * @return the {@link AuthorizationManager} */ public AuthorizationManager<HttpServletRequest> getAuthorizationManager() { return this.authorizationManager; } /** * Sets whether to filter all dispatcher types. * @param shouldFilterAllDispatcherTypes should filter all dispatcher types. Default * is {@code true} * @since 5.7 * @deprecated Permit access to the {@link jakarta.servlet.DispatcherType} instead. * <pre> * &#064;Configuration * &#064;EnableWebSecurity * public class SecurityConfig { * * &#064;Bean * public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { * http * .authorizeHttpRequests((authorize) -&gt; authorize * .dispatcherTypeMatchers(DispatcherType.ERROR).permitAll() * // ... * ); * return http.build(); * } * } * </pre> */ @Deprecated(since = "6.1", forRemoval = true) public void setShouldFilterAllDispatcherTypes(boolean shouldFilterAllDispatcherTypes) { this.observeOncePerRequest = !shouldFilterAllDispatcherTypes; this.filterErrorDispatch = shouldFilterAllDispatcherTypes; this.filterAsyncDispatch = shouldFilterAllDispatcherTypes; } private static <T> void noPublish(Supplier<Authentication> authentication, T object, AuthorizationDecision decision) { } public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } /** * Sets whether this filter apply only once per request. By default, this is * <code>false</code>, meaning the filter will execute on every request. Sometimes * users may wish it to execute more than once per request, such as when JSP forwards * are being used and filter security is desired on each included fragment of the HTTP * request. * @param observeOncePerRequest whether the filter should only be applied once per * request */ public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } /** * If set to true, the filter will be applied to error dispatcher. Defaults to * {@code true}. * @param filterErrorDispatch whether the filter should be applied to error dispatcher */ public void setFilterErrorDispatch(boolean filterErrorDispatch) { this.filterErrorDispatch = filterErrorDispatch; } /** * If set to true, the filter will be applied to the async dispatcher. Defaults to * {@code true}. * @param filterAsyncDispatch whether the filter should be applied to async dispatch */ public void setFilterAsyncDispatch(boolean filterAsyncDispatch) { this.filterAsyncDispatch = filterAsyncDispatch; } }
8,578
34.895397
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.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.servlet.util.matcher; import java.util.Map; import java.util.Objects; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpMethod; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestVariablesExtractor; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import org.springframework.web.servlet.handler.MatchableHandlerMapping; import org.springframework.web.servlet.handler.RequestMatchResult; import org.springframework.web.util.UrlPathHelper; /** * A {@link RequestMatcher} that uses Spring MVC's {@link HandlerMappingIntrospector} to * match the path and extract variables. * * <p> * It is important to understand that Spring MVC's matching is relative to the servlet * path. This means if you have mapped any servlet to a path that starts with "/" and is * greater than one, you should also specify the {@link #setServletPath(String)} attribute * to differentiate mappings. * </p> * * @author Rob Winch * @author Eddú Meléndez * @author Evgeniy Cheban * @since 4.1.1 */ public class MvcRequestMatcher implements RequestMatcher, RequestVariablesExtractor { private final DefaultMatcher defaultMatcher = new DefaultMatcher(); private final HandlerMappingIntrospector introspector; private final String pattern; private HttpMethod method; private String servletPath; public MvcRequestMatcher(HandlerMappingIntrospector introspector, String pattern) { this.introspector = introspector; this.pattern = pattern; } @Override public boolean matches(HttpServletRequest request) { if (notMatchMethodOrServletPath(request)) { return false; } MatchableHandlerMapping mapping = getMapping(request); if (mapping == null) { return this.defaultMatcher.matches(request); } RequestMatchResult matchResult = mapping.match(request, this.pattern); return matchResult != null; } @Override @Deprecated public Map<String, String> extractUriTemplateVariables(HttpServletRequest request) { return matcher(request).getVariables(); } @Override public MatchResult matcher(HttpServletRequest request) { if (notMatchMethodOrServletPath(request)) { return MatchResult.notMatch(); } MatchableHandlerMapping mapping = getMapping(request); if (mapping == null) { return this.defaultMatcher.matcher(request); } RequestMatchResult result = mapping.match(request, this.pattern); return (result != null) ? MatchResult.match(result.extractUriTemplateVariables()) : MatchResult.notMatch(); } private boolean notMatchMethodOrServletPath(HttpServletRequest request) { return this.method != null && !this.method.name().equals(request.getMethod()) || this.servletPath != null && !this.servletPath.equals(request.getServletPath()); } private MatchableHandlerMapping getMapping(HttpServletRequest request) { try { return this.introspector.getMatchableHandlerMapping(request); } catch (Throwable ex) { return null; } } /** * @param method the method to set */ public void setMethod(HttpMethod method) { this.method = method; } /** * The servlet path to match on. The default is undefined which means any servlet * path. * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } protected final String getServletPath() { return this.servletPath; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MvcRequestMatcher that = (MvcRequestMatcher) o; return Objects.equals(this.pattern, that.pattern) && Objects.equals(this.method, that.method) && Objects.equals(this.servletPath, that.servletPath); } @Override public int hashCode() { return Objects.hash(this.pattern, this.method, this.servletPath); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Mvc [pattern='").append(this.pattern).append("'"); if (this.servletPath != null) { sb.append(", servletPath='").append(this.servletPath).append("'"); } if (this.method != null) { sb.append(", ").append(this.method); } sb.append("]"); return sb.toString(); } private class DefaultMatcher implements RequestMatcher { private final UrlPathHelper pathHelper = new UrlPathHelper(); private final PathMatcher pathMatcher = new AntPathMatcher(); @Override public boolean matches(HttpServletRequest request) { String lookupPath = this.pathHelper.getLookupPathForRequest(request); return matches(lookupPath); } private boolean matches(String lookupPath) { return this.pathMatcher.match(MvcRequestMatcher.this.pattern, lookupPath); } @Override public MatchResult matcher(HttpServletRequest request) { String lookupPath = this.pathHelper.getLookupPathForRequest(request); if (matches(lookupPath)) { Map<String, String> variables = this.pathMatcher .extractUriTemplateVariables(MvcRequestMatcher.this.pattern, lookupPath); return MatchResult.match(variables); } return MatchResult.notMatch(); } } /** * A builder for {@link MvcRequestMatcher} * * @author Marcus Da Coregio * @since 5.8 */ public static final class Builder { private final HandlerMappingIntrospector introspector; private String servletPath; /** * Construct a new instance of this builder */ public Builder(HandlerMappingIntrospector introspector) { this.introspector = introspector; } /** * Sets the servlet path to be used by the {@link MvcRequestMatcher} generated by * this builder * @param servletPath the servlet path to use * @return the {@link Builder} for further configuration */ public Builder servletPath(String servletPath) { this.servletPath = servletPath; return this; } /** * Creates an {@link MvcRequestMatcher} that uses the provided pattern to match * @param pattern the pattern used to match * @return the generated {@link MvcRequestMatcher} */ public MvcRequestMatcher pattern(String pattern) { return pattern(null, pattern); } /** * Creates an {@link MvcRequestMatcher} that uses the provided pattern and HTTP * method to match * @param method the {@link HttpMethod}, can be null * @param pattern the patterns used to match * @return the generated {@link MvcRequestMatcher} */ public MvcRequestMatcher pattern(HttpMethod method, String pattern) { MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(this.introspector, pattern); mvcRequestMatcher.setServletPath(this.servletPath); mvcRequestMatcher.setMethod(method); return mvcRequestMatcher; } } }
7,517
29.072
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.java
/* * Copyright 2002-2013 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.servlet.support.csrf; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.web.servlet.support.RequestDataValueProcessor; /** * Integration with Spring Web MVC that automatically adds the {@link CsrfToken} into * forms with hidden inputs when using Spring tag libraries. * * @author Rob Winch * @since 3.2 */ public final class CsrfRequestDataValueProcessor implements RequestDataValueProcessor { private Pattern DISABLE_CSRF_TOKEN_PATTERN = Pattern.compile("(?i)^(GET|HEAD|TRACE|OPTIONS)$"); private String DISABLE_CSRF_TOKEN_ATTR = "DISABLE_CSRF_TOKEN_ATTR"; public String processAction(HttpServletRequest request, String action) { return action; } @Override public String processAction(HttpServletRequest request, String action, String method) { if (method != null && this.DISABLE_CSRF_TOKEN_PATTERN.matcher(method).matches()) { request.setAttribute(this.DISABLE_CSRF_TOKEN_ATTR, Boolean.TRUE); } else { request.removeAttribute(this.DISABLE_CSRF_TOKEN_ATTR); } return action; } @Override public String processFormFieldValue(HttpServletRequest request, String name, String value, String type) { return value; } @Override public Map<String, String> getExtraHiddenFields(HttpServletRequest request) { if (Boolean.TRUE.equals(request.getAttribute(this.DISABLE_CSRF_TOKEN_ATTR))) { request.removeAttribute(this.DISABLE_CSRF_TOKEN_ATTR); return Collections.emptyMap(); } CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (token == null) { return Collections.emptyMap(); } Map<String, String> hiddenFields = new HashMap<>(1); hiddenFields.put(token.getParameterName(), token.getToken()); return hiddenFields; } @Override public String processUrl(HttpServletRequest request, String url) { return url; } }
2,665
31.120482
106
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jaasapi/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Makes a JAAS Subject available as the current Subject. * <p> * To use, simply add the {@code JaasApiIntegrationFilter} to the Spring Security filter * chain. */ package org.springframework.security.web.jaasapi;
845
34.25
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java
/* * Copyright 2010-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.jaasapi; import java.io.IOException; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.jaas.JaasAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * <p> * A <code>Filter</code> which attempts to obtain a JAAS <code>Subject</code> and continue * the <code>FilterChain</code> running as that <code>Subject</code>. * </p> * <p> * By using this <code>Filter</code> in conjunction with Spring's * <code>JaasAuthenticationProvider</code> both Spring's <code>SecurityContext</code> and * a JAAS <code>Subject</code> can be populated simultaneously. This is useful when * integrating with code that requires a JAAS <code>Subject</code> to be populated. * </p> * * @author Rob Winch * @see #doFilter(ServletRequest, ServletResponse, FilterChain) * @see #obtainSubject(ServletRequest) */ public class JaasApiIntegrationFilter extends GenericFilterBean { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private boolean createEmptySubject; /** * <p> * Attempts to obtain and run as a JAAS <code>Subject</code> using * {@link #obtainSubject(ServletRequest)}. * </p> * * <p> * If the <code>Subject</code> is <code>null</code> and <tt>createEmptySubject</tt> is * <code>true</code>, an empty, writeable <code>Subject</code> is used. This allows * for the <code>Subject</code> to be populated at the time of login. If the * <code>Subject</code> is <code>null</code>, the <code>FilterChain</code> continues * with no additional processing. If the <code>Subject</code> is not <code>null</code> * , the <code>FilterChain</code> is ran with * {@link Subject#doAs(Subject, PrivilegedExceptionAction)} in conjunction with the * <code>Subject</code> obtained. * </p> */ @Override public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { Subject subject = obtainSubject(request); if (subject == null && this.createEmptySubject) { this.logger.debug("Subject returned was null and createEmptySubject is true; " + "creating new empty subject to run as."); subject = new Subject(); } if (subject == null) { this.logger.debug("Subject is null continue running with no Subject."); chain.doFilter(request, response); return; } this.logger.debug(LogMessage.format("Running as Subject %s", subject)); try { Subject.doAs(subject, (PrivilegedExceptionAction<Object>) () -> { chain.doFilter(request, response); return null; }); } catch (PrivilegedActionException ex) { throw new ServletException(ex.getMessage(), ex); } } /** * <p> * Obtains the <code>Subject</code> to run as or <code>null</code> if no * <code>Subject</code> is available. * </p> * <p> * The default implementation attempts to obtain the <code>Subject</code> from the * <code>SecurityContext</code>'s <code>Authentication</code>. If it is of type * <code>JaasAuthenticationToken</code> and is authenticated, the <code>Subject</code> * is returned from it. Otherwise, <code>null</code> is returned. * </p> * @param request the current <code>ServletRequest</code> * @return the Subject to run as or <code>null</code> if no <code>Subject</code> is * available. */ protected Subject obtainSubject(ServletRequest request) { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); this.logger.debug(LogMessage.format("Attempting to obtainSubject using authentication : %s", authentication)); if (authentication == null) { return null; } if (!authentication.isAuthenticated()) { return null; } if (!(authentication instanceof JaasAuthenticationToken)) { return null; } JaasAuthenticationToken token = (JaasAuthenticationToken) authentication; LoginContext loginContext = token.getLoginContext(); if (loginContext == null) { return null; } return loginContext.getSubject(); } /** * Sets <code>createEmptySubject</code>. If the value is <code>true</code>, and * {@link #obtainSubject(ServletRequest)} returns <code>null</code>, an empty, * writeable <code>Subject</code> is created instead. Otherwise no * <code>Subject</code> is used. The default is <code>false</code>. * @param createEmptySubject the new value */ public final void setCreateEmptySubject(boolean createEmptySubject) { this.createEmptySubject = createEmptySubject; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
6,281
37.304878
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/package-info.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Authentication processing mechanisms, which respond to the submission of authentication * credentials using various protocols (eg BASIC, CAS, form login etc). */ package org.springframework.security.web.authentication;
851
37.727273
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.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.authentication; import java.io.IOException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * A {@link Filter} 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 #setRequestMatcher(RequestMatcher)}, then this filter does nothing and the * {@link FilterChain} is continued. If it does match then...</li> * <li>An attempt to convert the {@link HttpServletRequest} into an {@link Authentication} * is made. If the result is empty, then the filter does nothing more and the * {@link FilterChain} is continued. If it does create an {@link Authentication}...</li> * <li>The {@link AuthenticationManager} specified in * {@link #AuthenticationFilter(AuthenticationManager, AuthenticationConverter)} is used * to perform authentication.</li> * <li>The {@link AuthenticationManagerResolver} specified in * {@link #AuthenticationFilter(AuthenticationManagerResolver, AuthenticationConverter)} * is used to resolve the appropriate authentication manager from context to perform * authentication.</li> * <li>If authentication is successful, {@link AuthenticationSuccessHandler} is invoked * and the authentication is set on {@link SecurityContextHolder}, else * {@link AuthenticationFailureHandler} is invoked</li> * </ul> * * @author Sergey Bespalov * @since 5.2.0 */ public class AuthenticationFilter extends OncePerRequestFilter { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE; private AuthenticationConverter authenticationConverter; private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); private AuthenticationFailureHandler failureHandler = new AuthenticationEntryPointFailureHandler( new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository(); private AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver; public AuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationConverter authenticationConverter) { this((AuthenticationManagerResolver<HttpServletRequest>) (r) -> authenticationManager, authenticationConverter); } public AuthenticationFilter(AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver, AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null"); Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; this.authenticationConverter = authenticationConverter; } public RequestMatcher getRequestMatcher() { return this.requestMatcher; } public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } public AuthenticationConverter getAuthenticationConverter() { return this.authenticationConverter; } public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } public AuthenticationSuccessHandler getSuccessHandler() { return this.successHandler; } public void setSuccessHandler(AuthenticationSuccessHandler successHandler) { Assert.notNull(successHandler, "successHandler cannot be null"); this.successHandler = successHandler; } public AuthenticationFailureHandler getFailureHandler() { return this.failureHandler; } public void setFailureHandler(AuthenticationFailureHandler failureHandler) { Assert.notNull(failureHandler, "failureHandler cannot be null"); this.failureHandler = failureHandler; } public AuthenticationManagerResolver<HttpServletRequest> getAuthenticationManagerResolver() { return this.authenticationManagerResolver; } public void setAuthenticationManagerResolver( AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver) { Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.requestMatcher.matches(request)) { if (logger.isTraceEnabled()) { logger.trace("Did not match request to " + this.requestMatcher); } filterChain.doFilter(request, response); return; } try { Authentication authenticationResult = attemptAuthentication(request, response); if (authenticationResult == null) { filterChain.doFilter(request, response); return; } HttpSession session = request.getSession(false); if (session != null) { request.changeSessionId(); } successfulAuthentication(request, response, filterChain, authenticationResult); } catch (AuthenticationException ex) { unsuccessfulAuthentication(request, response, ex); } } private void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { this.securityContextHolderStrategy.clearContext(); this.failureHandler.onAuthenticationFailure(request, response, failed); } private void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); this.successHandler.onAuthenticationSuccess(request, response, chain, authentication); } private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, ServletException { Authentication authentication = this.authenticationConverter.convert(request); if (authentication == null) { return null; } AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authentication); if (authenticationResult == null) { throw new ServletException("AuthenticationManager should not return null Authentication object."); } return authenticationResult; } }
9,741
42.106195
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import java.io.IOException; import java.util.List; import java.util.function.Supplier; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationDetailsSource; 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.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.util.Assert; import org.springframework.util.function.SingletonSupplier; import org.springframework.web.filter.GenericFilterBean; /** * Detects if there is no {@code Authentication} object in the * {@code SecurityContextHolder}, and populates it with one if needed. * * @author Ben Alex * @author Luke Taylor * @author Evgeniy Cheban */ public class AnonymousAuthenticationFilter extends GenericFilterBean implements InitializingBean { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource(); 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 AnonymousAuthenticationFilter(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 AnonymousAuthenticationFilter(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 void afterPropertiesSet() { Assert.hasLength(this.key, "key must have length"); Assert.notNull(this.principal, "Anonymous authentication principal must be set"); Assert.notNull(this.authorities, "Anonymous authorities must be set"); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Supplier<SecurityContext> deferredContext = this.securityContextHolderStrategy.getDeferredContext(); this.securityContextHolderStrategy .setDeferredContext(defaultWithAnonymous((HttpServletRequest) req, deferredContext)); chain.doFilter(req, res); } private Supplier<SecurityContext> defaultWithAnonymous(HttpServletRequest request, Supplier<SecurityContext> currentDeferredContext) { return SingletonSupplier.of(() -> { SecurityContext currentContext = currentDeferredContext.get(); return defaultWithAnonymous(request, currentContext); }); } private SecurityContext defaultWithAnonymous(HttpServletRequest request, SecurityContext currentContext) { Authentication currentAuthentication = currentContext.getAuthentication(); if (currentAuthentication == null) { Authentication anonymous = createAuthentication(request); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Set SecurityContextHolder to " + anonymous)); } else { this.logger.debug("Set SecurityContextHolder to anonymous SecurityContext"); } SecurityContext anonymousContext = this.securityContextHolderStrategy.createEmptyContext(); anonymousContext.setAuthentication(anonymous); return anonymousContext; } else { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Did not set SecurityContextHolder since already authenticated " + currentAuthentication)); } } return currentContext; } protected Authentication createAuthentication(HttpServletRequest request) { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(this.key, this.principal, this.authorities); token.setDetails(this.authenticationDetailsSource.buildDetails(request)); return token; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } public Object getPrincipal() { return this.principal; } public List<GrantedAuthority> getAuthorities() { return this.authorities; } }
6,506
37.964072
127
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/NullRememberMeServices.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; /** * Implementation of {@link NullRememberMeServices} that does nothing. * <p> * Used as a default by several framework classes. * </p> * * @author Ben Alex */ public class NullRememberMeServices implements RememberMeServices { @Override public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { return null; } @Override public void loginFail(HttpServletRequest request, HttpServletResponse response) { } @Override public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { } }
1,446
28.530612
92
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandler.java
/* * Copyright 2002-2015 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.authentication; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.util.Assert; /** * An {@link AuthenticationFailureHandler} that delegates to other * {@link AuthenticationFailureHandler} instances based upon the type of * {@link AuthenticationException} passed into * {@link #onAuthenticationFailure(HttpServletRequest, HttpServletResponse, AuthenticationException)} * . * * @author Kazuki Shimizu * @since 4.0 */ public class DelegatingAuthenticationFailureHandler implements AuthenticationFailureHandler { private final LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers; private final AuthenticationFailureHandler defaultHandler; /** * Creates a new instance * @param handlers a map of the {@link AuthenticationException} class to the * {@link AuthenticationFailureHandler} that should be used. Each is considered in the * order they are specified and only the first {@link AuthenticationFailureHandler} is * ued. This parameter cannot specify null or empty. * @param defaultHandler the default {@link AuthenticationFailureHandler} that should * be used if none of the handlers matches. This parameter cannot specify null. * @throws IllegalArgumentException if invalid argument is specified */ public DelegatingAuthenticationFailureHandler( LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers, AuthenticationFailureHandler defaultHandler) { Assert.notEmpty(handlers, "handlers cannot be null or empty"); Assert.notNull(defaultHandler, "defaultHandler cannot be null"); this.handlers = handlers; this.defaultHandler = defaultHandler; } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { for (Map.Entry<Class<? extends AuthenticationException>, AuthenticationFailureHandler> entry : this.handlers .entrySet()) { Class<? extends AuthenticationException> handlerMappedExceptionClass = entry.getKey(); if (handlerMappedExceptionClass.isAssignableFrom(exception.getClass())) { AuthenticationFailureHandler handler = entry.getValue(); handler.onAuthenticationFailure(request, response, exception); return; } } this.defaultHandler.onAuthenticationFailure(request, response, exception); } }
3,319
39.987654
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetailsSource.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationDetailsSource; /** * Implementation of {@link AuthenticationDetailsSource} which builds the details object * from an <tt>HttpServletRequest</tt> object, creating a {@code WebAuthenticationDetails} * . * * @author Ben Alex */ public class WebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> { /** * @param context the {@code HttpServletRequest} object. * @return the {@code WebAuthenticationDetails} containing information about the * current request */ @Override public WebAuthenticationDetails buildDetails(HttpServletRequest context) { return new WebAuthenticationDetails(context); } }
1,476
32.568182
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.security.core.Authentication; import org.springframework.security.web.WebAttributes; /** * <tt>AuthenticationSuccessHandler</tt> which can be configured with a default URL which * users should be sent to upon successful authentication. * <p> * The logic used is that of the {@link AbstractAuthenticationTargetUrlRequestHandler * parent class}. * * @author Luke Taylor * @since 3.0 */ public class SimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler { public SimpleUrlAuthenticationSuccessHandler() { } /** * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base class. * @param defaultTargetUrl the URL to which the user should be redirected on * successful authentication. */ public SimpleUrlAuthenticationSuccessHandler(String defaultTargetUrl) { setDefaultTargetUrl(defaultTargetUrl); } /** * Calls the parent class {@code handle()} method to forward or redirect to the target * URL, and then calls {@code clearAuthenticationAttributes()} to remove any leftover * session data. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { handle(request, response, authentication); clearAuthenticationAttributes(request); } /** * Removes temporary authentication-related data which may have been stored in the * session during the authentication process. */ protected final void clearAuthenticationAttributes(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } } }
2,687
33.461538
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/RememberMeServices.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; /** * Implement by a class that is capable of providing a remember-me service. * * <p> * Spring Security filters (namely * {@link org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter * AbstractAuthenticationProcessingFilter} and * {@link org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter * RememberMeAuthenticationFilter} will call the methods provided by an implementation of * this interface. * <p> * Implementations may implement any type of remember-me capability they wish. Rolling * cookies (as per <a href= * "https://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice"> * https://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice</a>) can * be used, as can simple implementations that don't require a persistent store. * Implementations also determine the validity period of a remember-me cookie. This * interface has been designed to accommodate any of these remember-me models. * <p> * This interface does not define how remember-me services should offer a "cancel all * remember-me tokens" type capability, as this will be implementation specific and * requires no hooks into Spring Security. * * @author Ben Alex */ public interface RememberMeServices { /** * This method will be called whenever the <code>SecurityContextHolder</code> does not * contain an <code>Authentication</code> object and Spring Security wishes to provide * an implementation with an opportunity to authenticate the request using remember-me * capabilities. Spring Security makes no attempt whatsoever to determine whether the * browser has requested remember-me services or presented a valid cookie. Such * determinations are left to the implementation. If a browser has presented an * unauthorised cookie for whatever reason, it should be silently ignored and * invalidated using the <code>HttpServletResponse</code> object. * <p> * The returned <code>Authentication</code> must be acceptable to * {@link org.springframework.security.authentication.AuthenticationManager} or * {@link org.springframework.security.authentication.AuthenticationProvider} defined * by the web application. It is recommended * {@link org.springframework.security.authentication.RememberMeAuthenticationToken} * be used in most cases, as it has a corresponding authentication provider. * @param request to look for a remember-me token within * @param response to change, cancel or modify the remember-me token * @return a valid authentication object, or <code>null</code> if the request should * not be authenticated */ Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); /** * Called whenever an interactive authentication attempt was made, but the credentials * supplied by the user were missing or otherwise invalid. Implementations should * invalidate any and all remember-me tokens indicated in the * <code>HttpServletRequest</code>. * @param request that contained an invalid authentication request * @param response to change, cancel or modify the remember-me token */ void loginFail(HttpServletRequest request, HttpServletResponse response); /** * Called whenever an interactive authentication attempt is successful. An * implementation may automatically set a remember-me token in the * <code>HttpServletResponse</code>, although this is not recommended. Instead, * implementations should typically look for a request parameter that indicates the * browser has presented an explicit request for authentication to be remembered, such * as the presence of a HTTP POST parameter. * @param request that contained the valid authentication request * @param response to change, cancel or modify the remember-me token * @param successfulAuthentication representing the successfully authenticated * principal */ void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication); }
4,899
48
99
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AuthenticationConverter.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.authentication; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; /** * A strategy used for converting from a {@link HttpServletRequest} to an * {@link Authentication} of particular type. Used to authenticate with appropriate * {@link AuthenticationManager}. If the result is null, then it signals that no * authentication attempt should be made. It is also possible to throw * {@link AuthenticationException} within the {@link #convert(HttpServletRequest)} if * there was invalid Authentication scheme value. * * @author Sergey Bespalov * @since 5.2.0 */ public interface AuthenticationConverter { Authentication convert(HttpServletRequest request); }
1,528
36.292683
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationSuccessHandler.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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; /** * <p> * Forward Authentication Success Handler * </p> * * @author Shazin Sadakath * @since 4.1 * */ public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private final String forwardUrl; /** * @param forwardUrl */ public ForwardAuthenticationSuccessHandler(String forwardUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> "'" + forwardUrl + "' is not a valid forward URL"); this.forwardUrl = forwardUrl; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { request.getRequestDispatcher(this.forwardUrl).forward(request, response); } }
1,750
29.719298
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.util.StringUtils; /** * An authentication success strategy which can make use of the * {@link org.springframework.security.web.savedrequest.DefaultSavedRequest} which may * have been stored in the session by the {@link ExceptionTranslationFilter}. When such a * request is intercepted and requires authentication, the request data is stored to * record the original destination before the authentication process commenced, and to * allow the request to be reconstructed when a redirect to the same URL occurs. This * class is responsible for performing the redirect to the original URL if appropriate. * <p> * Following a successful authentication, it decides on the redirect destination, based on * the following scenarios: * <ul> * <li>If the {@code alwaysUseDefaultTargetUrl} property is set to true, the * {@code defaultTargetUrl} will be used for the destination. Any * {@code DefaultSavedRequest} stored in the session will be removed.</li> * <li>If the {@code targetUrlParameter} has been set on the request, the value will be * used as the destination. Any {@code DefaultSavedRequest} will again be removed.</li> * <li>If a {@link org.springframework.security.web.savedrequest.SavedRequest} is found in * the {@code RequestCache} (as set by the {@link ExceptionTranslationFilter} to record * the original destination before the authentication process commenced), a redirect will * be performed to the Url of that original destination. The {@code SavedRequest} object * will remain cached and be picked up when the redirected request is received (See * <a href=" * {@docRoot}/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.html">SavedRequestAwareWrapper</a>). * </li> * <li>If no {@link org.springframework.security.web.savedrequest.SavedRequest} is found, * it will delegate to the base class.</li> * </ul> * * @author Luke Taylor * @since 3.0 */ public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { protected final Log logger = LogFactory.getLog(this.getClass()); private RequestCache requestCache = new HttpSessionRequestCache(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = this.requestCache.getRequest(request, response); if (savedRequest == null) { super.onAuthenticationSuccess(request, response, authentication); return; } String targetUrlParameter = getTargetUrlParameter(); if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { this.requestCache.removeRequest(request, response); super.onAuthenticationSuccess(request, response, authentication); return; } clearAuthenticationAttributes(request); // Use the DefaultSavedRequest URL String targetUrl = savedRequest.getRedirectUrl(); getRedirectStrategy().sendRedirect(request, response, targetUrl); } public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } }
4,469
44.612245
121
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AuthenticationSuccessHandler.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; /** * Strategy used to handle a successful user authentication. * <p> * Implementations can do whatever they want but typical behaviour would be to control the * navigation to the subsequent destination (using a redirect or a forward). For example, * after a user has logged in by submitting a login form, the application needs to decide * where they should be redirected to afterwards (see * {@link AbstractAuthenticationProcessingFilter} and subclasses). Other logic may also be * included if required. * * @author Luke Taylor * @since 3.0 */ public interface AuthenticationSuccessHandler { /** * Called when a user has been successfully authenticated. * @param request the request which caused the successful authentication * @param response the response * @param chain the {@link FilterChain} which can be used to proceed other filters in * the chain * @param authentication the <tt>Authentication</tt> object which was created during * the authentication process. * @since 5.2.0 */ default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { onAuthenticationSuccess(request, response, authentication); chain.doFilter(request, response); } /** * Called when a user has been successfully authenticated. * @param request the request which caused the successful authentication * @param response the response * @param authentication the <tt>Authentication</tt> object which was created during * the authentication process. */ void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException; }
2,711
37.742857
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFailureHandler.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.AuthenticationException; /** * Strategy used to handle a failed authentication attempt. * <p> * Typical behaviour might be to redirect the user to the authentication page (in the case * of a form login) to allow them to try again. More sophisticated logic might be * implemented depending on the type of the exception. For example, a * {@link CredentialsExpiredException} might cause a redirect to a web controller which * allowed the user to change their password. * * @author Luke Taylor * @since 3.0 */ public interface AuthenticationFailureHandler { /** * Called when an authentication attempt fails. * @param request the request during which the authentication attempt occurred. * @param response the response. * @param exception the exception which was thrown to reject the authentication * request. */ void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException; }
1,972
36.226415
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandler.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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; /** * <p> * Forward Authentication Failure Handler * </p> * * @author Shazin Sadakath * @since 4.1 */ public class ForwardAuthenticationFailureHandler implements AuthenticationFailureHandler { private final String forwardUrl; /** * @param forwardUrl */ public ForwardAuthenticationFailureHandler(String forwardUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> "'" + forwardUrl + "' is not a valid forward URL"); this.forwardUrl = forwardUrl; } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); request.getRequestDispatcher(this.forwardUrl).forward(request, response); } }
1,890
31.603448
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; /** * <tt>AuthenticationFailureHandler</tt> which performs a redirect to the value of the * {@link #setDefaultFailureUrl defaultFailureUrl} property when the * <tt>onAuthenticationFailure</tt> method is called. If the property has not been set it * will send a 401 response to the client, with the error message from the * <tt>AuthenticationException</tt> which caused the failure. * <p> * If the {@code useForward} property is set, a {@code RequestDispatcher.forward} call * will be made to the destination instead of a redirect. * * @author Luke Taylor * @since 3.0 */ public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler { protected final Log logger = LogFactory.getLog(getClass()); private String defaultFailureUrl; private boolean forwardToDestination = false; private boolean allowSessionCreation = true; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); public SimpleUrlAuthenticationFailureHandler() { } public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) { setDefaultFailureUrl(defaultFailureUrl); } /** * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise * returns a 401 error code. * <p> * If redirecting or forwarding, {@code saveException} will be called to cache the * exception for use in the target view. */ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (this.defaultFailureUrl == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Sending 401 Unauthorized error since no failure URL is set"); } else { this.logger.debug("Sending 401 Unauthorized error"); } response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); return; } saveException(request, exception); if (this.forwardToDestination) { this.logger.debug("Forwarding to " + this.defaultFailureUrl); request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response); } else { this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl); } } /** * Caches the {@code AuthenticationException} for use in view rendering. * <p> * If {@code forwardToDestination} is set to true, request scope will be used, * otherwise it will attempt to store the exception in the session. If there is no * session and {@code allowSessionCreation} is {@code true} a session will be created. * Otherwise the exception will not be stored. */ protected final void saveException(HttpServletRequest request, AuthenticationException exception) { if (this.forwardToDestination) { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); return; } HttpSession session = request.getSession(false); if (session != null || this.allowSessionCreation) { request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); } } /** * The URL which will be used as the failure destination. * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp". */ public void setDefaultFailureUrl(String defaultFailureUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), () -> "'" + defaultFailureUrl + "' is not a valid redirect URL"); this.defaultFailureUrl = defaultFailureUrl; } protected boolean isUseForward() { return this.forwardToDestination; } /** * If set to <tt>true</tt>, performs a forward to the failure destination URL instead * of a redirect. Defaults to <tt>false</tt>. */ public void setUseForward(boolean forwardToDestination) { this.forwardToDestination = forwardToDestination; } /** * Allows overriding of the behaviour when redirecting to a target URL. */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } protected boolean isAllowSessionCreation() { return this.allowSessionCreation; } public void setAllowSessionCreation(boolean allowSessionCreation) { this.allowSessionCreation = allowSessionCreation; } }
5,656
34.578616
100
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/HttpStatusEntryPoint.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.util.Assert; /** * An {@link AuthenticationEntryPoint} 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 Rob Winch * @since 4.0 */ public final class HttpStatusEntryPoint implements AuthenticationEntryPoint { private final HttpStatus httpStatus; /** * Creates a new instance. * @param httpStatus the HttpStatus to set */ public HttpStatusEntryPoint(HttpStatus httpStatus) { Assert.notNull(httpStatus, "httpStatus cannot be null"); this.httpStatus = httpStatus; } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { response.setStatus(this.httpStatus.value()); } }
1,790
31.563636
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/NoOpAuthenticationEntryPoint.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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; /** * An {@link AuthenticationEntryPoint} implementation that does nothing. * * @author Marcus da Coregio * @since 6.2 */ public class NoOpAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { } }
1,369
30.860465
80
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * Abstract processor of browser-based HTTP-based authentication requests. * * <h3>Authentication Process</h3> * * The filter requires that you set the <tt>authenticationManager</tt> property. An * <tt>AuthenticationManager</tt> is required to process the authentication request tokens * created by implementing classes. * <p> * This filter will intercept a request and attempt to perform authentication from that * request if the request matches the * {@link #setRequiresAuthenticationRequestMatcher(RequestMatcher)}. * <p> * Authentication is performed by the * {@link #attemptAuthentication(HttpServletRequest, HttpServletResponse) * attemptAuthentication} method, which must be implemented by subclasses. * * <h4>Authentication Success</h4> * * If authentication is successful, the resulting {@link Authentication} object will be * placed into the <code>SecurityContext</code> for the current thread, which is * guaranteed to have already been created by an earlier filter. * <p> * The configured {@link #setAuthenticationSuccessHandler(AuthenticationSuccessHandler) * AuthenticationSuccessHandler} will then be called to take the redirect to the * appropriate destination after a successful login. The default behaviour is implemented * in a {@link SavedRequestAwareAuthenticationSuccessHandler} which will make use of any * <tt>DefaultSavedRequest</tt> set by the <tt>ExceptionTranslationFilter</tt> and * redirect the user to the URL contained therein. Otherwise it will redirect to the * webapp root "/". You can customize this behaviour by injecting a differently configured * instance of this class, or by using a different implementation. * <p> * See the * {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} * method for more information. * * <h4>Authentication Failure</h4> * * If authentication fails, it will delegate to the configured * {@link AuthenticationFailureHandler} to allow the failure information to be conveyed to * the client. The default implementation is {@link SimpleUrlAuthenticationFailureHandler} * , which sends a 401 error code to the client. It may also be configured with a failure * URL as an alternative. Again you can inject whatever behaviour you require here. * * <h4>Event Publication</h4> * * If authentication is successful, an {@link InteractiveAuthenticationSuccessEvent} will * be published via the application context. No events will be published if authentication * was unsuccessful, because this would generally be recorded via an * {@code AuthenticationManager}-specific application event. * * <h4>Session Authentication</h4> * * The class has an optional {@link SessionAuthenticationStrategy} which will be invoked * immediately after a successful call to {@code attemptAuthentication()}. Different * implementations {@link #setSessionAuthenticationStrategy(SessionAuthenticationStrategy) * can be injected} to enable things like session-fixation attack prevention or to control * the number of simultaneous sessions a principal may have. * * @author Ben Alex * @author Luke Taylor */ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean implements ApplicationEventPublisherAware, MessageSourceAware { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); protected ApplicationEventPublisher eventPublisher; protected AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource(); private AuthenticationManager authenticationManager; protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private RememberMeServices rememberMeServices = new NullRememberMeServices(); private RequestMatcher requiresAuthenticationRequestMatcher; private boolean continueChainBeforeSuccessfulAuthentication = false; private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy(); private boolean allowSessionCreation = true; private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository(); /** * @param defaultFilterProcessesUrl the default value for <tt>filterProcessesUrl</tt>. */ protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { setFilterProcessesUrl(defaultFilterProcessesUrl); } /** * Creates a new instance * @param requiresAuthenticationRequestMatcher the {@link RequestMatcher} used to * determine if authentication is required. Cannot be null. */ protected AbstractAuthenticationProcessingFilter(RequestMatcher requiresAuthenticationRequestMatcher) { Assert.notNull(requiresAuthenticationRequestMatcher, "requiresAuthenticationRequestMatcher cannot be null"); this.requiresAuthenticationRequestMatcher = requiresAuthenticationRequestMatcher; } /** * Creates a new instance with a default filterProcessesUrl and an * {@link AuthenticationManager} * @param defaultFilterProcessesUrl the default value for <tt>filterProcessesUrl</tt>. * @param authenticationManager the {@link AuthenticationManager} used to authenticate * an {@link Authentication} object. Cannot be null. */ protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) { setFilterProcessesUrl(defaultFilterProcessesUrl); setAuthenticationManager(authenticationManager); } /** * Creates a new instance with a {@link RequestMatcher} and an * {@link AuthenticationManager} * @param requiresAuthenticationRequestMatcher the {@link RequestMatcher} used to * determine if authentication is required. Cannot be null. * @param authenticationManager the {@link AuthenticationManager} used to authenticate * an {@link Authentication} object. Cannot be null. */ protected AbstractAuthenticationProcessingFilter(RequestMatcher requiresAuthenticationRequestMatcher, AuthenticationManager authenticationManager) { setRequiresAuthenticationRequestMatcher(requiresAuthenticationRequestMatcher); setAuthenticationManager(authenticationManager); } @Override public void afterPropertiesSet() { Assert.notNull(this.authenticationManager, "authenticationManager must be specified"); } /** * Invokes the {@link #requiresAuthentication(HttpServletRequest, HttpServletResponse) * requiresAuthentication} method to determine whether the request is for * authentication and should be handled by this filter. If it is an authentication * request, the {@link #attemptAuthentication(HttpServletRequest, HttpServletResponse) * attemptAuthentication} will be invoked to perform the authentication. There are * then three possible outcomes: * <ol> * <li>An <tt>Authentication</tt> object is returned. The configured * {@link SessionAuthenticationStrategy} will be invoked (to handle any * session-related behaviour such as creating a new session to protect against * session-fixation attacks) followed by the invocation of * {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} * method</li> * <li>An <tt>AuthenticationException</tt> occurs during authentication. The * {@link #unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) * unsuccessfulAuthentication} method will be invoked</li> * <li>Null is returned, indicating that the authentication process is incomplete. The * method will then return immediately, assuming that the subclass has done any * necessary work (such as redirects) to continue the authentication process. The * assumption is that a later request will be received by this method where the * returned <tt>Authentication</tt> object is not null. * </ol> */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (!requiresAuthentication(request, response)) { chain.doFilter(request, response); return; } try { Authentication authenticationResult = attemptAuthentication(request, response); if (authenticationResult == null) { // return immediately as subclass has indicated that it hasn't completed return; } this.sessionStrategy.onAuthentication(authenticationResult, request, response); // Authentication success if (this.continueChainBeforeSuccessfulAuthentication) { chain.doFilter(request, response); } successfulAuthentication(request, response, chain, authenticationResult); } catch (InternalAuthenticationServiceException failed) { this.logger.error("An internal error occurred while trying to authenticate the user.", failed); unsuccessfulAuthentication(request, response, failed); } catch (AuthenticationException ex) { // Authentication failed unsuccessfulAuthentication(request, response, ex); } } /** * Indicates whether this filter should attempt to process a login request for the * current invocation. * <p> * It strips any parameters from the "path" section of the request URL (such as the * jsessionid parameter in <em>https://host/myapp/index.html;jsessionid=blah</em>) * before matching against the <code>filterProcessesUrl</code> property. * <p> * Subclasses may override for special requirements, such as Tapestry integration. * @return <code>true</code> if the filter should attempt authentication, * <code>false</code> otherwise. */ protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { if (this.requiresAuthenticationRequestMatcher.matches(request)) { return true; } if (this.logger.isTraceEnabled()) { this.logger .trace(LogMessage.format("Did not match request to %s", this.requiresAuthenticationRequestMatcher)); } return false; } /** * Performs actual authentication. * <p> * The implementation should do one of the following: * <ol> * <li>Return a populated authentication token for the authenticated user, indicating * successful authentication</li> * <li>Return null, indicating that the authentication process is still in progress. * Before returning, the implementation should perform any additional work required to * complete the process.</li> * <li>Throw an <tt>AuthenticationException</tt> if the authentication process * fails</li> * </ol> * @param request from which to extract parameters and perform the authentication * @param response the response, which may be needed if the implementation has to do a * redirect as part of a multi-stage authentication process (such as OIDC). * @return the authenticated user token, or null if authentication is incomplete. * @throws AuthenticationException if authentication fails. */ public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException; /** * Default behaviour for successful authentication. * <ol> * <li>Sets the successful <tt>Authentication</tt> object on the * {@link SecurityContextHolder}</li> * <li>Informs the configured <tt>RememberMeServices</tt> of the successful login</li> * <li>Fires an {@link InteractiveAuthenticationSuccessEvent} via the configured * <tt>ApplicationEventPublisher</tt></li> * <li>Delegates additional behaviour to the * {@link AuthenticationSuccessHandler}.</li> * </ol> * * Subclasses can override this method to continue the {@link FilterChain} after * successful authentication. * @param request * @param response * @param chain * @param authResult the object returned from the <tt>attemptAuthentication</tt> * method. * @throws IOException * @throws ServletException */ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult)); } this.rememberMeServices.loginSuccess(request, response, authResult); if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } this.successHandler.onAuthenticationSuccess(request, response, authResult); } /** * Default behaviour for unsuccessful authentication. * <ol> * <li>Clears the {@link SecurityContextHolder}</li> * <li>Stores the exception in the session (if it exists or * <tt>allowSesssionCreation</tt> is set to <tt>true</tt>)</li> * <li>Informs the configured <tt>RememberMeServices</tt> of the failed login</li> * <li>Delegates additional behaviour to the * {@link AuthenticationFailureHandler}.</li> * </ol> */ protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { this.securityContextHolderStrategy.clearContext(); this.logger.trace("Failed to process authentication request", failed); this.logger.trace("Cleared SecurityContextHolder"); this.logger.trace("Handling authentication failure"); this.rememberMeServices.loginFail(request, response); this.failureHandler.onAuthenticationFailure(request, response, failed); } protected AuthenticationManager getAuthenticationManager() { return this.authenticationManager; } public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } /** * Sets the URL that determines if authentication is required * @param filterProcessesUrl */ public void setFilterProcessesUrl(String filterProcessesUrl) { setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(filterProcessesUrl)); } public final void setRequiresAuthenticationRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requiresAuthenticationRequestMatcher = requestMatcher; } public RememberMeServices getRememberMeServices() { return this.rememberMeServices; } public void setRememberMeServices(RememberMeServices rememberMeServices) { Assert.notNull(rememberMeServices, "rememberMeServices cannot be null"); this.rememberMeServices = rememberMeServices; } /** * Indicates if the filter chain should be continued prior to delegation to * {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} * , which may be useful in certain environment (such as Tapestry applications). * Defaults to <code>false</code>. */ public void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication) { this.continueChainBeforeSuccessfulAuthentication = continueChainBeforeSuccessfulAuthentication; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } protected boolean getAllowSessionCreation() { return this.allowSessionCreation; } public void setAllowSessionCreation(boolean allowSessionCreation) { this.allowSessionCreation = allowSessionCreation; } /** * The session handling strategy which will be invoked immediately after an * authentication request is successfully processed by the * <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the * session identifier to prevent session fixation attacks. * @param sessionStrategy the implementation to use. If not set a null implementation * is used. */ public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) { this.sessionStrategy = sessionStrategy; } /** * Sets the strategy used to handle a successful authentication. By default a * {@link SavedRequestAwareAuthenticationSuccessHandler} is used. */ public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) { Assert.notNull(successHandler, "successHandler cannot be null"); this.successHandler = successHandler; } public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { Assert.notNull(failureHandler, "failureHandler cannot be null"); this.failureHandler = failureHandler; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } protected AuthenticationSuccessHandler getSuccessHandler() { return this.successHandler; } protected AuthenticationFailureHandler getFailureHandler() { return this.failureHandler; } }
21,499
43.885177
129
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.authentication; import java.io.IOException; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.log.LogMessage; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.PortMapper; import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.PortResolver; import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.util.RedirectUrlBuilder; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Used by the {@link ExceptionTranslationFilter} to commence a form login authentication * via the {@link UsernamePasswordAuthenticationFilter}. * <p> * Holds the location of the login form in the {@code loginFormUrl} property, and uses * that to build a redirect URL to the login page. Alternatively, an absolute URL can be * set in this property and that will be used exclusively. * <p> * When using a relative URL, you can set the {@code forceHttps} property to true, to * force the protocol used for the login form to be {@code HTTPS}, even if the original * intercepted request for a resource used the {@code HTTP} protocol. When this happens, * after a successful login (via HTTPS), the original resource will still be accessed as * HTTP, via the original request URL. For the forced HTTPS feature to work, the * {@link PortMapper} is consulted to determine the HTTP:HTTPS pairs. The value of * {@code forceHttps} will have no effect if an absolute URL is used. * * @author Ben Alex * @author colin sampaleanu * @author Omri Spector * @author Luke Taylor * @since 3.0 */ public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean { private static final Log logger = LogFactory.getLog(LoginUrlAuthenticationEntryPoint.class); private PortMapper portMapper = new PortMapperImpl(); private PortResolver portResolver = new PortResolverImpl(); private String loginFormUrl; private boolean forceHttps = false; private boolean useForward = false; private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * @param loginFormUrl URL where the login page can be found. Should either be * relative to the web-app context path (include a leading {@code /}) or an absolute * URL. */ public LoginUrlAuthenticationEntryPoint(String loginFormUrl) { Assert.notNull(loginFormUrl, "loginFormUrl cannot be null"); this.loginFormUrl = loginFormUrl; } @Override public void afterPropertiesSet() { Assert.isTrue(StringUtils.hasText(this.loginFormUrl) && UrlUtils.isValidRedirectUrl(this.loginFormUrl), "loginFormUrl must be specified and must be a valid redirect URL"); Assert.isTrue(!this.useForward || !UrlUtils.isAbsoluteUrl(this.loginFormUrl), "useForward must be false if using an absolute loginFormURL"); Assert.notNull(this.portMapper, "portMapper must be specified"); Assert.notNull(this.portResolver, "portResolver must be specified"); } /** * Allows subclasses to modify the login form URL that should be applicable for a * given request. * @param request the request * @param response the response * @param exception the exception * @return the URL (cannot be null or empty; defaults to {@link #getLoginFormUrl()}) */ protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { return getLoginFormUrl(); } /** * Performs the redirect (or forward) to the login form URL. */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { if (!this.useForward) { // redirect to login page. Use https if forceHttps true String redirectUrl = buildRedirectUrlToLoginPage(request, response, authException); this.redirectStrategy.sendRedirect(request, response, redirectUrl); return; } String redirectUrl = null; if (this.forceHttps && "http".equals(request.getScheme())) { // First redirect the current request to HTTPS. When that request is received, // the forward to the login page will be used. redirectUrl = buildHttpsRedirectUrlForRequest(request); } if (redirectUrl != null) { this.redirectStrategy.sendRedirect(request, response, redirectUrl); return; } String loginForm = determineUrlToUseForThisRequest(request, response, authException); logger.debug(LogMessage.format("Server side forward to: %s", loginForm)); RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm); dispatcher.forward(request, response); return; } protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { String loginForm = determineUrlToUseForThisRequest(request, response, authException); if (UrlUtils.isAbsoluteUrl(loginForm)) { return loginForm; } int serverPort = this.portResolver.getServerPort(request); String scheme = request.getScheme(); RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder(); urlBuilder.setScheme(scheme); urlBuilder.setServerName(request.getServerName()); urlBuilder.setPort(serverPort); urlBuilder.setContextPath(request.getContextPath()); urlBuilder.setPathInfo(loginForm); if (this.forceHttps && "http".equals(scheme)) { Integer httpsPort = this.portMapper.lookupHttpsPort(serverPort); if (httpsPort != null) { // Overwrite scheme and port in the redirect URL urlBuilder.setScheme("https"); urlBuilder.setPort(httpsPort); } else { logger.warn(LogMessage.format("Unable to redirect to HTTPS as no port mapping found for HTTP port %s", serverPort)); } } return urlBuilder.getUrl(); } /** * Builds a URL to redirect the supplied request to HTTPS. Used to redirect the * current request to HTTPS, before doing a forward to the login page. */ protected String buildHttpsRedirectUrlForRequest(HttpServletRequest request) throws IOException, ServletException { int serverPort = this.portResolver.getServerPort(request); Integer httpsPort = this.portMapper.lookupHttpsPort(serverPort); if (httpsPort != null) { RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setServerName(request.getServerName()); urlBuilder.setPort(httpsPort); urlBuilder.setContextPath(request.getContextPath()); urlBuilder.setServletPath(request.getServletPath()); urlBuilder.setPathInfo(request.getPathInfo()); urlBuilder.setQuery(request.getQueryString()); return urlBuilder.getUrl(); } // Fall through to server-side forward with warning message logger.warn( LogMessage.format("Unable to redirect to HTTPS as no port mapping found for HTTP port %s", serverPort)); return null; } /** * Set to true to force login form access to be via https. If this value is true (the * default is false), and the incoming request for the protected resource which * triggered the interceptor was not already <code>https</code>, then the client will * first be redirected to an https URL, even if <tt>serverSideRedirect</tt> is set to * <tt>true</tt>. */ public void setForceHttps(boolean forceHttps) { this.forceHttps = forceHttps; } protected boolean isForceHttps() { return this.forceHttps; } public String getLoginFormUrl() { return this.loginFormUrl; } public void setPortMapper(PortMapper portMapper) { Assert.notNull(portMapper, "portMapper cannot be null"); this.portMapper = portMapper; } protected PortMapper getPortMapper() { return this.portMapper; } public void setPortResolver(PortResolver portResolver) { Assert.notNull(portResolver, "portResolver cannot be null"); this.portResolver = portResolver; } protected PortResolver getPortResolver() { return this.portResolver; } /** * Tells if we are to do a forward to the {@code loginFormUrl} using the * {@code RequestDispatcher}, instead of a 302 redirect. * @param useForward true if a forward to the login page should be used. Must be false * (the default) if {@code loginFormUrl} is set to an absolute value. */ public void setUseForward(boolean useForward) { this.useForward = useForward; } protected boolean isUseForward() { return this.useForward; } }
9,687
37.907631
116
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.java
/* * Copyright 2010-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.authentication; import java.io.IOException; import java.util.LinkedHashMap; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.log.LogMessage; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.util.matcher.ELRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcherEditor; import org.springframework.util.Assert; /** * An {@code AuthenticationEntryPoint} which selects a concrete * {@code AuthenticationEntryPoint} based on a {@link RequestMatcher} evaluation. * * <p> * A configuration might look like this: * </p> * * <pre> * &lt;bean id=&quot;daep&quot; class=&quot;org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint&quot;&gt; * &lt;constructor-arg&gt; * &lt;map&gt; * &lt;entry key=&quot;hasIpAddress('192.168.1.0/24') and hasHeader('User-Agent','Mozilla')&quot; value-ref=&quot;firstAEP&quot; /&gt; * &lt;entry key=&quot;hasHeader('User-Agent','MSIE')&quot; value-ref=&quot;secondAEP&quot; /&gt; * &lt;/map&gt; * &lt;/constructor-arg&gt; * &lt;property name=&quot;defaultEntryPoint&quot; ref=&quot;defaultAEP&quot;/&gt; * &lt;/bean&gt; * </pre> * * This example uses the {@link RequestMatcherEditor} which creates a * {@link ELRequestMatcher} instances for the map keys. * * @author Mike Wiesner * @since 3.0.2 */ public class DelegatingAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean { private static final Log logger = LogFactory.getLog(DelegatingAuthenticationEntryPoint.class); private final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints; private AuthenticationEntryPoint defaultEntryPoint; public DelegatingAuthenticationEntryPoint(LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints) { this.entryPoints = entryPoints; } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { for (RequestMatcher requestMatcher : this.entryPoints.keySet()) { logger.debug(LogMessage.format("Trying to match using %s", requestMatcher)); if (requestMatcher.matches(request)) { AuthenticationEntryPoint entryPoint = this.entryPoints.get(requestMatcher); logger.debug(LogMessage.format("Match found! Executing %s", entryPoint)); entryPoint.commence(request, response, authException); return; } } logger.debug(LogMessage.format("No match found. Using default entry point %s", this.defaultEntryPoint)); // No EntryPoint matched, use defaultEntryPoint this.defaultEntryPoint.commence(request, response, authException); } /** * EntryPoint which is used when no RequestMatcher returned true */ public void setDefaultEntryPoint(AuthenticationEntryPoint defaultEntryPoint) { this.defaultEntryPoint = defaultEntryPoint; } @Override public void afterPropertiesSet() { Assert.notEmpty(this.entryPoints, "entryPoints must be specified"); Assert.notNull(this.defaultEntryPoint, "defaultEntryPoint must be specified"); } }
4,209
38.716981
146
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandler.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.authentication; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.core.Authentication; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Base class containing the logic used by strategies which handle redirection to a URL * and are passed an {@code Authentication} object as part of the contract. See * {@link AuthenticationSuccessHandler} and * {@link org.springframework.security.web.authentication.logout.LogoutSuccessHandler * LogoutSuccessHandler}, for example. * <p> * Uses the following logic sequence to determine how it should handle the * forward/redirect * <ul> * <li>If the {@code alwaysUseDefaultTargetUrl} property is set to true, the * {@code defaultTargetUrl} property will be used for the destination.</li> * <li>If a parameter matching the value of {@code targetUrlParameter} has been set on the * request, the value will be used as the destination. If you are enabling this * functionality, then you should ensure that the parameter cannot be used by an attacker * to redirect the user to a malicious site (by clicking on a URL with the parameter * included, for example). Typically it would be used when the parameter is included in * the login form and submitted with the username and password.</li> * <li>If the {@code useReferer} property is set, the "Referer" HTTP header value will be * used, if present.</li> * <li>As a fallback option, the {@code defaultTargetUrl} value will be used.</li> * </ul> * * @author Luke Taylor * @since 3.0 */ public abstract class AbstractAuthenticationTargetUrlRequestHandler { protected final Log logger = LogFactory.getLog(this.getClass()); private String targetUrlParameter = null; private String defaultTargetUrl = "/"; private boolean alwaysUseDefaultTargetUrl = false; private boolean useReferer = false; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); protected AbstractAuthenticationTargetUrlRequestHandler() { } /** * Invokes the configured {@code RedirectStrategy} with the URL returned by the * {@code determineTargetUrl} method. * <p> * The redirect will not be performed if the response has already been committed. */ protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String targetUrl = determineTargetUrl(request, response, authentication); if (response.isCommitted()) { this.logger.debug(LogMessage.format("Did not redirect to %s since response already committed.", targetUrl)); return; } this.redirectStrategy.sendRedirect(request, response, targetUrl); } /** * Builds the target URL according to the logic defined in the main class Javadoc * @since 5.2 */ protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { return determineTargetUrl(request, response); } /** * Builds the target URL according to the logic defined in the main class Javadoc. */ protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { if (isAlwaysUseDefaultTargetUrl()) { return this.defaultTargetUrl; } String targetUrlParameterValue = getTargetUrlParameterValue(request); if (StringUtils.hasText(targetUrlParameterValue)) { trace("Using url %s from request parameter %s", targetUrlParameterValue, this.targetUrlParameter); return targetUrlParameterValue; } if (this.useReferer) { trace("Using url %s from Referer header", request.getHeader("Referer")); return request.getHeader("Referer"); } return this.defaultTargetUrl; } private String getTargetUrlParameterValue(HttpServletRequest request) { if (this.targetUrlParameter == null) { return null; } String value = request.getParameter(this.targetUrlParameter); if (value == null) { return null; } if (StringUtils.hasText(value)) { return value; } return this.defaultTargetUrl; } private void trace(String msg, String... msgParts) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format(msg, msgParts)); } } /** * Supplies the default target Url that will be used if no saved request is found or * the {@code alwaysUseDefaultTargetUrl} property is set to true. If not set, defaults * to {@code /}. * @return the defaultTargetUrl property */ protected final String getDefaultTargetUrl() { return this.defaultTargetUrl; } /** * Supplies the default target Url that will be used if no saved request is found in * the session, or the {@code alwaysUseDefaultTargetUrl} property is set to true. If * not set, defaults to {@code /}. It will be treated as relative to the web-app's * context path, and should include the leading <code>/</code>. Alternatively, * inclusion of a scheme name (such as "http://" or "https://") as the prefix will * denote a fully-qualified URL and this is also supported. * @param defaultTargetUrl */ public void setDefaultTargetUrl(String defaultTargetUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultTargetUrl), "defaultTarget must start with '/' or with 'http(s)'"); this.defaultTargetUrl = defaultTargetUrl; } /** * If <code>true</code>, will always redirect to the value of {@code defaultTargetUrl} * (defaults to <code>false</code>). */ public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl) { this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl; } protected boolean isAlwaysUseDefaultTargetUrl() { return this.alwaysUseDefaultTargetUrl; } /** * If this property is set, the current request will be checked for this a parameter * with this name and the value used as the target URL if present. * @param targetUrlParameter the name of the parameter containing the encoded target * URL. Defaults to null. */ public void setTargetUrlParameter(String targetUrlParameter) { if (targetUrlParameter != null) { Assert.hasText(targetUrlParameter, "targetUrlParameter cannot be empty"); } this.targetUrlParameter = targetUrlParameter; } protected String getTargetUrlParameter() { return this.targetUrlParameter; } /** * Allows overriding of the behaviour when redirecting to a target URL. */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } /** * If set to {@code true} the {@code Referer} header will be used (if available). * Defaults to {@code false}. */ public void setUseReferer(boolean useReferer) { this.useReferer = useReferer; } }
7,843
35.314815
111
java