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/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepository.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.saml2.provider.service.web.authentication.logout; import java.security.MessageDigest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.util.Assert; /** * An implementation of an {@link Saml2LogoutRequestRepository} that stores * {@link Saml2LogoutRequest} in the {@code HttpSession}. * * @author Josh Cummings * @since 5.6 * @see Saml2LogoutRequestRepository * @see Saml2LogoutRequest */ public final class HttpSessionLogoutRequestRepository implements Saml2LogoutRequestRepository { private static final String DEFAULT_LOGOUT_REQUEST_ATTR_NAME = HttpSessionLogoutRequestRepository.class.getName() + ".LOGOUT_REQUEST"; /** * {@inheritDoc} */ @Override public Saml2LogoutRequest loadLogoutRequest(HttpServletRequest request) { Assert.notNull(request, "request cannot be null"); HttpSession session = request.getSession(false); if (session == null) { return null; } Saml2LogoutRequest logoutRequest = (Saml2LogoutRequest) session.getAttribute(DEFAULT_LOGOUT_REQUEST_ATTR_NAME); if (stateParameterEquals(request, logoutRequest)) { return logoutRequest; } return null; } /** * {@inheritDoc} */ @Override public void saveLogoutRequest(Saml2LogoutRequest logoutRequest, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); if (logoutRequest == null) { request.getSession().removeAttribute(DEFAULT_LOGOUT_REQUEST_ATTR_NAME); return; } String state = logoutRequest.getRelayState(); Assert.hasText(state, "logoutRequest.state cannot be empty"); request.getSession().setAttribute(DEFAULT_LOGOUT_REQUEST_ATTR_NAME, logoutRequest); } /** * {@inheritDoc} */ @Override public Saml2LogoutRequest removeLogoutRequest(HttpServletRequest request, HttpServletResponse response) { Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); Saml2LogoutRequest logoutRequest = loadLogoutRequest(request); if (logoutRequest == null) { return null; } request.getSession().removeAttribute(DEFAULT_LOGOUT_REQUEST_ATTR_NAME); return logoutRequest; } private String getStateParameter(HttpServletRequest request) { return request.getParameter(Saml2ParameterNames.RELAY_STATE); } private boolean stateParameterEquals(HttpServletRequest request, Saml2LogoutRequest logoutRequest) { String stateParameter = getStateParameter(request); if (stateParameter == null || logoutRequest == null) { return false; } String relayState = logoutRequest.getRelayState(); return MessageDigest.isEqual(Utf8.encode(stateParameter), Utf8.encode(relayState)); } }
3,697
33.560748
114
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestRepository.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.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; /** * Implementations of this interface are responsible for the persistence of * {@link Saml2LogoutRequest} between requests. * * <p> * Used by the {@link Saml2RelyingPartyInitiatedLogoutSuccessHandler} for persisting the * Logout Request before it initiates the SAML 2.0 SLO flow. As well, used by * {@code OpenSamlLogoutResponseHandler} for resolving the Logout Request associated with * that Logout Response. * * @author Josh Cummings * @since 5.6 * @see Saml2LogoutRequest * @see HttpSessionLogoutRequestRepository */ public interface Saml2LogoutRequestRepository { /** * Returns the {@link Saml2LogoutRequest} associated to the provided * {@code HttpServletRequest} or {@code null} if not available. * @param request the {@code HttpServletRequest} * @return the {@link Saml2LogoutRequest} or {@code null} if not available */ Saml2LogoutRequest loadLogoutRequest(HttpServletRequest request); /** * Persists the {@link Saml2LogoutRequest} associating it to the provided * {@code HttpServletRequest} and/or {@code HttpServletResponse}. * @param logoutRequest the {@link Saml2LogoutRequest} * @param request the {@code HttpServletRequest} * @param response the {@code HttpServletResponse} */ void saveLogoutRequest(Saml2LogoutRequest logoutRequest, HttpServletRequest request, HttpServletResponse response); /** * Removes and returns the {@link Saml2LogoutRequest} associated to the provided * {@code HttpServletRequest} and {@code HttpServletResponse} or if not available * returns {@code null}. * @param request the {@code HttpServletRequest} * @param response the {@code HttpServletResponse} * @return the {@link Saml2LogoutRequest} or {@code null} if not available */ Saml2LogoutRequest removeLogoutRequest(HttpServletRequest request, HttpServletResponse response); }
2,744
38.782609
116
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestValidatorParametersResolver.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.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; /** * Resolved a SAML 2.0 Logout Request and associated validation parameters from the given * {@link HttpServletRequest} and current {@link Authentication}. * * The returned logout request is suitable for validating, logging out the logged-in user, * and initiating the construction of a {@code LogoutResponse}. * * @author Josh Cummings * @since 6.1 */ public interface Saml2LogoutRequestValidatorParametersResolver { /** * Resolve any SAML 2.0 Logout Request and associated * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration} * @param request the HTTP request * @param authentication the current user, if any; may be null * @return a SAML 2.0 Logout Request, if any; may be null */ Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication); }
1,804
38.23913
119
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.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.saml2.provider.service.web.authentication.logout; 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.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriComponentsBuilder; /** * A success handler for issuing a SAML 2.0 Logout Request to the the SAML 2.0 Asserting * Party * * @author Josh Cummings * @since 5.6 */ public final class Saml2RelyingPartyInitiatedLogoutSuccessHandler implements LogoutSuccessHandler { private final Log logger = LogFactory.getLog(getClass()); private final Saml2LogoutRequestResolver logoutRequestResolver; private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private Saml2LogoutRequestRepository logoutRequestRepository = new HttpSessionLogoutRequestRepository(); /** * Constructs a {@link Saml2RelyingPartyInitiatedLogoutSuccessHandler} using the * provided parameters * @param logoutRequestResolver the {@link Saml2LogoutRequestResolver} to use */ public Saml2RelyingPartyInitiatedLogoutSuccessHandler(Saml2LogoutRequestResolver logoutRequestResolver) { this.logoutRequestResolver = logoutRequestResolver; } /** * Produce and send a SAML 2.0 Logout Response based on the SAML 2.0 Logout Request * received from the asserting party * @param request the HTTP request * @param response the HTTP response * @param authentication the current principal details * @throws IOException when failing to write to the response */ @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(request, authentication); if (logoutRequest == null) { this.logger.trace("Returning 401 since no logout request generated"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); if (logoutRequest.getBinding() == Saml2MessageBinding.REDIRECT) { doRedirect(request, response, logoutRequest); } else { doPost(response, logoutRequest); } } /** * Use this {@link Saml2LogoutRequestRepository} for saving the SAML 2.0 Logout * Request * @param logoutRequestRepository the {@link Saml2LogoutRequestRepository} to use */ public void setLogoutRequestRepository(Saml2LogoutRequestRepository logoutRequestRepository) { Assert.notNull(logoutRequestRepository, "logoutRequestRepository cannot be null"); this.logoutRequestRepository = logoutRequestRepository; } private void doRedirect(HttpServletRequest request, HttpServletResponse response, Saml2LogoutRequest logoutRequest) throws IOException { String location = logoutRequest.getLocation(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(location) .query(logoutRequest.getParametersQuery()); this.redirectStrategy.sendRedirect(request, response, uriBuilder.build(true).toUriString()); } private void doPost(HttpServletResponse response, Saml2LogoutRequest logoutRequest) throws IOException { String location = logoutRequest.getLocation(); String saml = logoutRequest.getSamlRequest(); String relayState = logoutRequest.getRelayState(); String html = createSamlPostRequestFormData(location, saml, relayState); response.setContentType(MediaType.TEXT_HTML_VALUE); response.getWriter().write(html); } private String createSamlPostRequestFormData(String location, String saml, String relayState) { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(location); html.append("\" method=\"post\">\n"); html.append(" <div>\n"); html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\""); html.append(HtmlUtils.htmlEscape(saml)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); } html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } }
6,775
41.35
117
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.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.saml2.provider.service.web.authentication.logout; import java.io.IOException; import jakarta.servlet.FilterChain; 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.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.logout.CompositeLogoutHandler; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriComponentsBuilder; /** * A filter for handling logout requests in the form of a &lt;saml2:LogoutRequest&gt; sent * from the asserting party. * * @author Josh Cummings * @since 5.6 * @see Saml2LogoutRequestValidator */ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { private final Log logger = LogFactory.getLog(getClass()); private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private final Saml2LogoutRequestValidatorParametersResolver logoutRequestResolver; private final Saml2LogoutRequestValidator logoutRequestValidator; private final Saml2LogoutResponseResolver logoutResponseResolver; private final LogoutHandler handler; private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); public Saml2LogoutRequestFilter(Saml2LogoutRequestValidatorParametersResolver logoutRequestResolver, Saml2LogoutRequestValidator logoutRequestValidator, Saml2LogoutResponseResolver logoutResponseResolver, LogoutHandler... handlers) { this.logoutRequestResolver = logoutRequestResolver; this.logoutRequestValidator = logoutRequestValidator; this.logoutResponseResolver = logoutResponseResolver; this.handler = new CompositeLogoutHandler(handlers); } /** * Constructs a {@link Saml2LogoutResponseFilter} for accepting SAML 2.0 Logout * Requests from the asserting party * @param relyingPartyRegistrationResolver the strategy for resolving a * {@link RelyingPartyRegistration} * @param logoutRequestValidator the SAML 2.0 Logout Request authenticator * @param logoutResponseResolver the strategy for creating a SAML 2.0 Logout Response * @param handlers the actions that perform logout */ public Saml2LogoutRequestFilter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver, Saml2LogoutRequestValidator logoutRequestValidator, Saml2LogoutResponseResolver logoutResponseResolver, LogoutHandler... handlers) { this.logoutRequestResolver = new Saml2AssertingPartyLogoutRequestResolver(relyingPartyRegistrationResolver); this.logoutRequestValidator = logoutRequestValidator; this.logoutResponseResolver = logoutResponseResolver; this.handler = new CompositeLogoutHandler(handlers); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); Saml2LogoutRequestValidatorParameters parameters; try { parameters = this.logoutRequestResolver.resolve(request, authentication); } catch (Saml2AuthenticationException ex) { this.logger.trace("Did not process logout request since failed to find requested RelyingPartyRegistration"); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (parameters == null) { chain.doFilter(request, response); return; } RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration(); if (registration.getSingleLogoutServiceLocation() == null) { this.logger.trace( "Did not process logout request since RelyingPartyRegistration has not been configured with a logout request endpoint"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); if (!registration.getSingleLogoutServiceBindings().contains(saml2MessageBinding)) { this.logger.trace("Did not process logout request since used incorrect binding"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } Saml2LogoutValidatorResult result = this.logoutRequestValidator.validate(parameters); if (result.hasErrors()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, result.getErrors().iterator().next().toString()); this.logger.debug(LogMessage.format("Failed to validate LogoutRequest: %s", result.getErrors())); return; } this.handler.logout(request, response, authentication); Saml2LogoutResponse logoutResponse = this.logoutResponseResolver.resolve(request, authentication); if (logoutResponse == null) { this.logger.trace("Returning 401 since no logout response generated"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } if (logoutResponse.getBinding() == Saml2MessageBinding.REDIRECT) { doRedirect(request, response, logoutResponse); } else { doPost(response, logoutResponse); } } public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); Assert.isInstanceOf(Saml2AssertingPartyLogoutRequestResolver.class, this.logoutRequestResolver, "saml2LogoutRequestResolver and logoutRequestMatcher cannot both be set. Please set the request matcher in the saml2LogoutRequestResolver itself."); ((Saml2AssertingPartyLogoutRequestResolver) this.logoutRequestResolver) .setLogoutRequestMatcher(logoutRequestMatcher); } /** * 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 void doRedirect(HttpServletRequest request, HttpServletResponse response, Saml2LogoutResponse logoutResponse) throws IOException { String location = logoutResponse.getResponseLocation(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(location) .query(logoutResponse.getParametersQuery()); this.redirectStrategy.sendRedirect(request, response, uriBuilder.build(true).toUriString()); } private void doPost(HttpServletResponse response, Saml2LogoutResponse logoutResponse) throws IOException { String location = logoutResponse.getResponseLocation(); String saml = logoutResponse.getSamlResponse(); String relayState = logoutResponse.getRelayState(); String html = createSamlPostRequestFormData(location, saml, relayState); response.setContentType(MediaType.TEXT_HTML_VALUE); response.getWriter().write(html); } private String createSamlPostRequestFormData(String location, String saml, String relayState) { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(location); html.append("\" method=\"post\">\n"); html.append(" <div>\n"); html.append(" <input type=\"hidden\" name=\"SAMLResponse\" value=\""); html.append(HtmlUtils.htmlEscape(saml)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); } html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } private static class Saml2AssertingPartyLogoutRequestResolver implements Saml2LogoutRequestValidatorParametersResolver { private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout/saml2/slo"); Saml2AssertingPartyLogoutRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; } @Override public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication) { String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); if (serialized == null) { return null; } RequestMatcher.MatchResult result = this.logoutRequestMatcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = getRegistrationId(result, authentication); RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, registrationId); if (registration == null) { throw new Saml2AuthenticationException( new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "registration not found"), "registration not found"); } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); registration = registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceLocation()) .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, request.getParameter(Saml2ParameterNames.SIG_ALG))) .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, request.getParameter(Saml2ParameterNames.SIGNATURE))) .parametersQuery((params) -> request.getQueryString()).build(); return new Saml2LogoutRequestValidatorParameters(logoutRequest, registration, authentication); } void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); this.logoutRequestMatcher = logoutRequestMatcher; } private String getRegistrationId(RequestMatcher.MatchResult result, Authentication authentication) { String registrationId = result.getVariables().get("registrationId"); if (registrationId != null) { return registrationId; } if (authentication == null) { return null; } if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal principal) { return principal.getRelyingPartyRegistrationId(); } return null; } } }
15,175
47.485623
152
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.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.saml2.provider.service.web.authentication.logout; import java.time.Clock; import java.time.Instant; import java.util.function.Consumer; import jakarta.servlet.http.HttpServletRequest; import org.opensaml.saml.saml2.core.LogoutResponse; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.util.Assert; /** * A {@link Saml2LogoutResponseResolver} for resolving SAML 2.0 Logout Responses with * OpenSAML 4 * * @author Josh Cummings * @since 5.6 */ public final class OpenSaml4LogoutResponseResolver implements Saml2LogoutResponseResolver { private final OpenSamlLogoutResponseResolver logoutResponseResolver; private Consumer<LogoutResponseParameters> parametersConsumer = (parameters) -> { }; private Clock clock = Clock.systemUTC(); public OpenSaml4LogoutResponseResolver(RelyingPartyRegistrationRepository registrations) { this.logoutResponseResolver = new OpenSamlLogoutResponseResolver(registrations, (request, id) -> { if (id == null) { return null; } return registrations.findByRegistrationId(id); }); } /** * Construct a {@link OpenSaml4LogoutResponseResolver} */ public OpenSaml4LogoutResponseResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.logoutResponseResolver = new OpenSamlLogoutResponseResolver(null, relyingPartyRegistrationResolver); } /** * {@inheritDoc} */ @Override public Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication) { return this.logoutResponseResolver.resolve(request, authentication, (registration, logoutResponse) -> { logoutResponse.setIssueInstant(Instant.now(this.clock)); this.parametersConsumer .accept(new LogoutResponseParameters(request, registration, authentication, logoutResponse)); }); } /** * Set a {@link Consumer} for modifying the OpenSAML {@link LogoutResponse} * @param parametersConsumer a consumer that accepts an * {@link LogoutResponseParameters} */ public void setParametersConsumer(Consumer<LogoutResponseParameters> parametersConsumer) { Assert.notNull(parametersConsumer, "parametersConsumer cannot be null"); this.parametersConsumer = parametersConsumer; } public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.clock = clock; } public static final class LogoutResponseParameters { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final Authentication authentication; private final LogoutResponse logoutResponse; public LogoutResponseParameters(HttpServletRequest request, RelyingPartyRegistration registration, Authentication authentication, LogoutResponse logoutResponse) { this.request = request; this.registration = registration; this.authentication = authentication; this.logoutResponse = logoutResponse; } public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public Authentication getAuthentication() { return this.authentication; } public LogoutResponse getLogoutResponse() { return this.logoutResponse; } } }
4,296
32.310078
108
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2MessageBindingUtils.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.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * Utility methods for working with {@link Saml2MessageBinding} * * For internal use only. * * @since 5.8 */ final class Saml2MessageBindingUtils { private Saml2MessageBindingUtils() { } static Saml2MessageBinding resolveBinding(HttpServletRequest request) { if (isHttpPostBinding(request)) { return Saml2MessageBinding.POST; } else if (isHttpRedirectBinding(request)) { return Saml2MessageBinding.REDIRECT; } throw new Saml2Exception("Unable to determine message binding from request."); } private static boolean isSamlRequestResponse(HttpServletRequest request) { return (request.getParameter(Saml2ParameterNames.SAML_REQUEST) != null || request.getParameter(Saml2ParameterNames.SAML_RESPONSE) != null); } static boolean isHttpRedirectBinding(HttpServletRequest request) { return request != null && "GET".equalsIgnoreCase(request.getMethod()) && isSamlRequestResponse(request); } static boolean isHttpPostBinding(HttpServletRequest request) { return request != null && "POST".equalsIgnoreCase(request.getMethod()) && isSamlRequestResponse(request); } }
2,086
33.213115
107
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.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.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * Creates a signed SAML 2.0 Logout Response based on information from the * {@link HttpServletRequest} and current {@link Authentication}. * * The returned logout response is suitable for sending to the asserting party based on, * for example, the location and binding specified in * {@link RelyingPartyRegistration#getAssertingPartyDetails()}. * * @author Josh Cummings * @since 5.6 * @see RelyingPartyRegistration */ public interface Saml2LogoutResponseResolver { /** * Prepare to create, sign, and serialize a SAML 2.0 Logout Response. * @param request the HTTP request * @param authentication the current user * @return a signed and serialized SAML 2.0 Logout Response */ Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication); }
1,813
36.791667
101
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.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.saml2.provider.service.web.authentication.logout; import java.time.Clock; import java.time.Instant; import java.util.function.Consumer; import jakarta.servlet.http.HttpServletRequest; import org.opensaml.saml.saml2.core.LogoutRequest; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.util.Assert; /** * A {@link Saml2LogoutRequestResolver} for resolving SAML 2.0 Logout Requests with * OpenSAML 4 * * @author Josh Cummings * @author Gerhard Haege * @since 5.6 */ public final class OpenSaml4LogoutRequestResolver implements Saml2LogoutRequestResolver { private final OpenSamlLogoutRequestResolver logoutRequestResolver; private Consumer<LogoutRequestParameters> parametersConsumer = (parameters) -> { }; private Clock clock = Clock.systemUTC(); public OpenSaml4LogoutRequestResolver(RelyingPartyRegistrationRepository registrations) { this((request, id) -> { if (id == null) { return null; } return registrations.findByRegistrationId(id); }); } /** * Construct a {@link OpenSaml4LogoutRequestResolver} */ public OpenSaml4LogoutRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.logoutRequestResolver = new OpenSamlLogoutRequestResolver(relyingPartyRegistrationResolver); } /** * {@inheritDoc} */ @Override public Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentication) { return this.logoutRequestResolver.resolve(request, authentication, (registration, logoutRequest) -> { logoutRequest.setIssueInstant(Instant.now(this.clock)); this.parametersConsumer .accept(new LogoutRequestParameters(request, registration, authentication, logoutRequest)); }); } /** * Set a {@link Consumer} for modifying the OpenSAML {@link LogoutRequest} * @param parametersConsumer a consumer that accepts an * {@link LogoutRequestParameters} */ public void setParametersConsumer(Consumer<LogoutRequestParameters> parametersConsumer) { Assert.notNull(parametersConsumer, "parametersConsumer cannot be null"); this.parametersConsumer = parametersConsumer; } /** * Use this {@link Clock} for determining the issued {@link Instant} * @param clock the {@link Clock} to use */ public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.clock = clock; } /** * Use this {@link Converter} to compute the RelayState * @param relayStateResolver the {@link Converter} to use * @since 6.1 */ public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.logoutRequestResolver.setRelayStateResolver(relayStateResolver); } public static final class LogoutRequestParameters { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final Authentication authentication; private final LogoutRequest logoutRequest; public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration, Authentication authentication, LogoutRequest logoutRequest) { this.request = request; this.registration = registration; this.authentication = authentication; this.logoutRequest = logoutRequest; } public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public Authentication getAuthentication() { return this.authentication; } public LogoutRequest getLogoutRequest() { return this.logoutRequest; } } }
4,776
31.944828
107
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestResolver.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.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * Creates a signed SAML 2.0 Logout Request based on information from the * {@link HttpServletRequest} and current {@link Authentication}. * * The returned logout request is suitable for sending to the asserting party based on, * for example, the location and binding specified in * {@link RelyingPartyRegistration#getAssertingPartyDetails()}. * * @author Josh Cummings * @since 5.6 * @see RelyingPartyRegistration */ public interface Saml2LogoutRequestResolver { /** * Prepare to create, sign, and serialize a SAML 2.0 Logout Request. * * By default, includes a {@code NameID} based on the {@link Authentication} instance. * @param request the HTTP request * @param authentication the current user * @return a signed and serialized SAML 2.0 Logout Request */ Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentication); }
1,898
36.98
100
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Utils.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.saml2.provider.service.authentication; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterOutputStream; import org.springframework.security.saml2.Saml2Exception; /** * @since 5.3 */ final class Saml2Utils { private Saml2Utils() { } static String samlEncode(byte[] b) { return Base64.getEncoder().encodeToString(b); } static byte[] samlDecode(String s) { return Base64.getMimeDecoder().decode(s); } static byte[] samlDeflate(String s) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true)); deflater.write(s.getBytes(StandardCharsets.UTF_8)); deflater.finish(); return b.toByteArray(); } catch (IOException ex) { throw new Saml2Exception("Unable to deflate string", ex); } } static String samlInflate(byte[] b) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException ex) { throw new Saml2Exception("Unable to inflate string", ex); } } }
2,097
27.739726
102
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlSigningUtils.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.saml2.provider.service.authentication; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; import org.opensaml.security.SecurityException; import org.opensaml.security.credential.BasicCredential; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.SignatureSigningParameters; import org.opensaml.xmlsec.SignatureSigningParametersResolver; import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; import org.opensaml.xmlsec.crypto.XMLSigningUtil; import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; import org.opensaml.xmlsec.signature.SignableXMLObject; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.opensaml.xmlsec.signature.support.SignatureSupport; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * Utility methods for signing SAML components with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlSigningUtils { static String serialize(XMLObject object) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } static <O extends SignableXMLObject> O sign(O object, RelyingPartyRegistration relyingPartyRegistration) { SignatureSigningParameters parameters = resolveSigningParameters(relyingPartyRegistration); try { SignatureSupport.signObject(object, parameters); return object; } catch (Exception ex) { throw new Saml2Exception(ex); } } static QueryParametersPartial sign(RelyingPartyRegistration registration) { return new QueryParametersPartial(registration); } private static SignatureSigningParameters resolveSigningParameters( RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration); List<String> algorithms = relyingPartyRegistration.getAssertingPartyDetails().getSigningAlgorithms(); List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); CriteriaSet criteria = new CriteriaSet(); BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); signingConfiguration.setSigningCredentials(credentials); signingConfiguration.setSignatureAlgorithms(algorithms); signingConfiguration.setSignatureReferenceDigestMethods(digests); signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration)); try { SignatureSigningParameters parameters = resolver.resolveSingle(criteria); Assert.notNull(parameters, "Failed to resolve any signing credential"); return parameters; } catch (Exception ex) { throw new Saml2Exception(ex); } } private static NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); namedManager.setUseDefaultManager(true); final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); // Generator for X509Credentials final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); x509Factory.setEmitEntityCertificate(true); x509Factory.setEmitEntityCertificateChain(true); defaultManager.registerFactory(x509Factory); return namedManager; } private static List<Credential> resolveSigningCredentials(RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential x509Credential : relyingPartyRegistration.getSigningX509Credentials()) { X509Certificate certificate = x509Credential.getCertificate(); PrivateKey privateKey = x509Credential.getPrivateKey(); BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); credential.setEntityId(relyingPartyRegistration.getEntityId()); credential.setUsageType(UsageType.SIGNING); credentials.add(credential); } return credentials; } private OpenSamlSigningUtils() { } static class QueryParametersPartial { final RelyingPartyRegistration registration; final Map<String, String> components = new LinkedHashMap<>(); QueryParametersPartial(RelyingPartyRegistration registration) { this.registration = registration; } QueryParametersPartial param(String key, String value) { this.components.put(key, value); return this; } Map<String, String> parameters() { SignatureSigningParameters parameters = resolveSigningParameters(this.registration); Credential credential = parameters.getSigningCredential(); String algorithmUri = parameters.getSignatureAlgorithm(); this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String> component : this.components.entrySet()) { builder.queryParam(component.getKey(), UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); } String queryString = builder.build(true).toString().substring(1); try { byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, queryString.getBytes(StandardCharsets.UTF_8)); String b64Signature = Saml2Utils.samlEncode(rawSignature); this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); } catch (SecurityException ex) { throw new Saml2Exception(ex); } return this.components; } } }
7,936
39.702564
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequest.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.saml2.provider.service.authentication; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * Data holder for information required to send an {@code AuthNRequest} over a REDIRECT * binding from the service provider to the identity provider * https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf * (line 2031) * * @since 5.3 * @see org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver */ public final class Saml2RedirectAuthenticationRequest extends AbstractSaml2AuthenticationRequest { private final String sigAlg; private final String signature; private Saml2RedirectAuthenticationRequest(String samlRequest, String sigAlg, String signature, String relayState, String authenticationRequestUri, String relyingPartyRegistrationId, String id) { super(samlRequest, relayState, authenticationRequestUri, relyingPartyRegistrationId, id); this.sigAlg = sigAlg; this.signature = signature; } /** * Returns the SigAlg value for {@link Saml2MessageBinding#REDIRECT} requests * @return the SigAlg value */ public String getSigAlg() { return this.sigAlg; } /** * Returns the Signature value for {@link Saml2MessageBinding#REDIRECT} requests * @return the Signature value */ public String getSignature() { return this.signature; } /** * @return {@link Saml2MessageBinding#REDIRECT} */ @Override public Saml2MessageBinding getBinding() { return Saml2MessageBinding.REDIRECT; } /** * Constructs a {@link Saml2PostAuthenticationRequest.Builder} from a * {@link RelyingPartyRegistration} object. * @param registration a relying party registration * @return a modifiable builder object * @since 5.7 */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { String location = registration.getAssertingPartyDetails().getSingleSignOnServiceLocation(); return new Builder(registration).authenticationRequestUri(location); } /** * Builder class for a {@link Saml2RedirectAuthenticationRequest} object. */ public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> { private String sigAlg; private String signature; private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Sets the {@code SigAlg} parameter that will accompany this AuthNRequest * @param sigAlg the SigAlg parameter value. * @return this object */ public Builder sigAlg(String sigAlg) { this.sigAlg = sigAlg; return _this(); } /** * Sets the {@code Signature} parameter that will accompany this AuthNRequest * @param signature the Signature parameter value. * @return this object */ public Builder signature(String signature) { this.signature = signature; return _this(); } /** * Constructs an immutable {@link Saml2RedirectAuthenticationRequest} object. * @return an immutable {@link Saml2RedirectAuthenticationRequest} object. */ public Saml2RedirectAuthenticationRequest build() { return new Saml2RedirectAuthenticationRequest(this.samlRequest, this.sigAlg, this.signature, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
4,097
31.784
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationProvider.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.saml2.provider.service.authentication; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import javax.annotation.Nonnull; import javax.xml.namespace.QName; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.schema.XSAny; import org.opensaml.core.xml.schema.XSBoolean; import org.opensaml.core.xml.schema.XSBooleanValue; import org.opensaml.core.xml.schema.XSDateTime; import org.opensaml.core.xml.schema.XSInteger; import org.opensaml.core.xml.schema.XSString; import org.opensaml.core.xml.schema.XSURI; import org.opensaml.saml.common.assertion.ValidationContext; import org.opensaml.saml.common.assertion.ValidationResult; import org.opensaml.saml.saml2.assertion.ConditionValidator; import org.opensaml.saml.saml2.assertion.SAML20AssertionValidator; import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters; import org.opensaml.saml.saml2.assertion.StatementValidator; import org.opensaml.saml.saml2.assertion.SubjectConfirmationValidator; import org.opensaml.saml.saml2.assertion.impl.AudienceRestrictionConditionValidator; import org.opensaml.saml.saml2.assertion.impl.BearerSubjectConfirmationValidator; import org.opensaml.saml.saml2.assertion.impl.DelegationRestrictionConditionValidator; import org.opensaml.saml.saml2.core.Assertion; import org.opensaml.saml.saml2.core.Attribute; import org.opensaml.saml.saml2.core.AttributeStatement; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.AuthnStatement; import org.opensaml.saml.saml2.core.Condition; import org.opensaml.saml.saml2.core.EncryptedAssertion; import org.opensaml.saml.saml2.core.OneTimeUse; import org.opensaml.saml.saml2.core.Response; import org.opensaml.saml.saml2.core.StatusCode; import org.opensaml.saml.saml2.core.SubjectConfirmation; import org.opensaml.saml.saml2.core.SubjectConfirmationData; import org.opensaml.saml.saml2.core.impl.AuthnRequestUnmarshaller; import org.opensaml.saml.saml2.core.impl.ResponseUnmarshaller; import org.opensaml.saml.saml2.encryption.Decrypter; import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; import org.opensaml.xmlsec.signature.support.SignaturePrevalidator; import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.core.convert.converter.Converter; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ResponseValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; /** * Implementation of {@link AuthenticationProvider} for SAML authentications when * receiving a {@code Response} object containing an {@code Assertion}. This * implementation uses the {@code OpenSAML 4} library. * * <p> * The {@link OpenSaml4AuthenticationProvider} supports {@link Saml2AuthenticationToken} * objects that contain a SAML response in its decoded XML format * {@link Saml2AuthenticationToken#getSaml2Response()} along with the information about * the asserting party, the identity provider (IDP), as well as the relying party, the * service provider (SP, this application). * <p> * The {@link Saml2AuthenticationToken} will be processed into a SAML Response object. The * SAML response object can be signed. If the Response is signed, a signature will not be * required on the assertion. * <p> * While a response object can contain a list of assertion, this provider will only * leverage the first valid assertion for the purpose of authentication. Assertions that * do not pass validation will be ignored. If no valid assertions are found a * {@link Saml2AuthenticationException} is thrown. * <p> * This provider supports two types of encrypted SAML elements * <ul> * <li><a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=17">EncryptedAssertion</a></li> * <li><a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=14">EncryptedID</a></li> * </ul> * If the assertion is encrypted, then signature validation on the assertion is no longer * required. * <p> * This provider does not perform an X509 certificate validation on the configured * asserting party, IDP, verification certificates. * * @author Josh Cummings * @since 5.5 * @see <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=38">SAML 2 * StatusResponse</a> * @see <a href="https://shibboleth.atlassian.net/wiki/spaces/OSAML/overview">OpenSAML</a> */ public final class OpenSaml4AuthenticationProvider implements AuthenticationProvider { static { OpenSamlInitializationService.initialize(); } private final Log logger = LogFactory.getLog(this.getClass()); private final ResponseUnmarshaller responseUnmarshaller; private static final AuthnRequestUnmarshaller authnRequestUnmarshaller; static { XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); authnRequestUnmarshaller = (AuthnRequestUnmarshaller) registry.getUnmarshallerFactory() .getUnmarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME); } private final ParserPool parserPool; private final Converter<ResponseToken, Saml2ResponseValidatorResult> responseSignatureValidator = createDefaultResponseSignatureValidator(); private Consumer<ResponseToken> responseElementsDecrypter = createDefaultResponseElementsDecrypter(); private Converter<ResponseToken, Saml2ResponseValidatorResult> responseValidator = createDefaultResponseValidator(); private final Converter<AssertionToken, Saml2ResponseValidatorResult> assertionSignatureValidator = createDefaultAssertionSignatureValidator(); private Consumer<AssertionToken> assertionElementsDecrypter = createDefaultAssertionElementsDecrypter(); private Converter<AssertionToken, Saml2ResponseValidatorResult> assertionValidator = createDefaultAssertionValidator(); private Converter<ResponseToken, ? extends AbstractAuthenticationToken> responseAuthenticationConverter = createDefaultResponseAuthenticationConverter(); /** * Creates an {@link OpenSaml4AuthenticationProvider} */ public OpenSaml4AuthenticationProvider() { XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.responseUnmarshaller = (ResponseUnmarshaller) registry.getUnmarshallerFactory() .getUnmarshaller(Response.DEFAULT_ELEMENT_NAME); this.parserPool = registry.getParserPool(); } /** * Set the {@link Consumer} strategy to use for decrypting elements of a validated * {@link Response}. The default strategy decrypts all {@link EncryptedAssertion}s * using OpenSAML's {@link Decrypter}, adding the results to * {@link Response#getAssertions()}. * * You can use this method to configure the {@link Decrypter} instance like so: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * provider.setResponseElementsDecrypter((responseToken) -&gt; { * DecrypterParameters parameters = new DecrypterParameters(); * // ... set parameters as needed * Decrypter decrypter = new Decrypter(parameters); * Response response = responseToken.getResponse(); * EncryptedAssertion encrypted = response.getEncryptedAssertions().get(0); * try { * Assertion assertion = decrypter.decrypt(encrypted); * response.getAssertions().add(assertion); * } catch (Exception e) { * throw new Saml2AuthenticationException(...); * } * }); * </pre> * * Or, in the event that you have your own custom decryption interface, the same * pattern applies: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * Converter&lt;EncryptedAssertion, Assertion&gt; myService = ... * provider.setResponseDecrypter((responseToken) -&gt; { * Response response = responseToken.getResponse(); * response.getEncryptedAssertions().stream() * .map(service::decrypt).forEach(response.getAssertions()::add); * }); * </pre> * * This is valuable when using an external service to perform the decryption. * @param responseElementsDecrypter the {@link Consumer} for decrypting response * elements * @since 5.5 */ public void setResponseElementsDecrypter(Consumer<ResponseToken> responseElementsDecrypter) { Assert.notNull(responseElementsDecrypter, "responseElementsDecrypter cannot be null"); this.responseElementsDecrypter = responseElementsDecrypter; } /** * Set the {@link Converter} to use for validating the SAML 2.0 Response. * * You can still invoke the default validator by delegating to * {@link #createDefaultResponseValidator()}, like so: * * <pre> * OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); * provider.setResponseValidator(responseToken -&gt; { * Saml2ResponseValidatorResult result = createDefaultResponseValidator() * .convert(responseToken) * return result.concat(myCustomValidator.convert(responseToken)); * }); * </pre> * @param responseValidator the {@link Converter} to use * @since 5.6 */ public void setResponseValidator(Converter<ResponseToken, Saml2ResponseValidatorResult> responseValidator) { Assert.notNull(responseValidator, "responseValidator cannot be null"); this.responseValidator = responseValidator; } /** * Set the {@link Converter} to use for validating each {@link Assertion} in the SAML * 2.0 Response. * * You can still invoke the default validator by delgating to * {@link #createAssertionValidator}, like so: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * provider.setAssertionValidator(assertionToken -&gt; { * Saml2ResponseValidatorResult result = createDefaultAssertionValidator() * .convert(assertionToken) * return result.concat(myCustomValidator.convert(assertionToken)); * }); * </pre> * * You can also use this method to configure the provider to use a different * {@link ValidationContext} from the default, like so: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * provider.setAssertionValidator( * createDefaultAssertionValidator(assertionToken -&gt; { * Map&lt;String, Object&gt; params = new HashMap&lt;&gt;(); * params.put(CLOCK_SKEW, 2 * 60 * 1000); * // other parameters * return new ValidationContext(params); * })); * </pre> * * Consider taking a look at {@link #createValidationContext} to see how it constructs * a {@link ValidationContext}. * * It is not necessary to delegate to the default validator. You can safely replace it * entirely with your own. Note that signature verification is performed as a separate * step from this validator. * @param assertionValidator the validator to use * @since 5.4 */ public void setAssertionValidator(Converter<AssertionToken, Saml2ResponseValidatorResult> assertionValidator) { Assert.notNull(assertionValidator, "assertionValidator cannot be null"); this.assertionValidator = assertionValidator; } /** * Set the {@link Consumer} strategy to use for decrypting elements of a validated * {@link Assertion}. * * You can use this method to configure the {@link Decrypter} used like so: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * provider.setResponseDecrypter((assertionToken) -&gt; { * DecrypterParameters parameters = new DecrypterParameters(); * // ... set parameters as needed * Decrypter decrypter = new Decrypter(parameters); * Assertion assertion = assertionToken.getAssertion(); * EncryptedID encrypted = assertion.getSubject().getEncryptedID(); * try { * NameID name = decrypter.decrypt(encrypted); * assertion.getSubject().setNameID(name); * } catch (Exception e) { * throw new Saml2AuthenticationException(...); * } * }); * </pre> * * Or, in the event that you have your own custom interface, the same pattern applies: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * MyDecryptionService myService = ... * provider.setResponseDecrypter((responseToken) -&gt; { * Assertion assertion = assertionToken.getAssertion(); * EncryptedID encrypted = assertion.getSubject().getEncryptedID(); * NameID name = myService.decrypt(encrypted); * assertion.getSubject().setNameID(name); * }); * </pre> * @param assertionDecrypter the {@link Consumer} for decrypting assertion elements * @since 5.5 */ public void setAssertionElementsDecrypter(Consumer<AssertionToken> assertionDecrypter) { Assert.notNull(assertionDecrypter, "assertionDecrypter cannot be null"); this.assertionElementsDecrypter = assertionDecrypter; } /** * Set the {@link Converter} to use for converting a validated {@link Response} into * an {@link AbstractAuthenticationToken}. * * You can delegate to the default behavior by calling * {@link #createDefaultResponseAuthenticationConverter()} like so: * * <pre> * OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); * Converter&lt;ResponseToken, Saml2Authentication&gt; authenticationConverter = * createDefaultResponseAuthenticationConverter(); * provider.setResponseAuthenticationConverter(responseToken -&gt; { * Saml2Authentication authentication = authenticationConverter.convert(responseToken); * User user = myUserRepository.findByUsername(authentication.getName()); * return new MyAuthentication(authentication, user); * }); * </pre> * @param responseAuthenticationConverter the {@link Converter} to use * @since 5.4 */ public void setResponseAuthenticationConverter( Converter<ResponseToken, ? extends AbstractAuthenticationToken> responseAuthenticationConverter) { Assert.notNull(responseAuthenticationConverter, "responseAuthenticationConverter cannot be null"); this.responseAuthenticationConverter = responseAuthenticationConverter; } /** * Construct a default strategy for validating the SAML 2.0 Response * @return the default response validator strategy * @since 5.6 */ public static Converter<ResponseToken, Saml2ResponseValidatorResult> createDefaultResponseValidator() { return (responseToken) -> { Response response = responseToken.getResponse(); Saml2AuthenticationToken token = responseToken.getToken(); Saml2ResponseValidatorResult result = Saml2ResponseValidatorResult.success(); String statusCode = getStatusCode(response); if (!StatusCode.SUCCESS.equals(statusCode)) { String message = String.format("Invalid status [%s] for SAML response [%s]", statusCode, response.getID()); result = result.concat(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, message)); } String inResponseTo = response.getInResponseTo(); result = result.concat(validateInResponseTo(token.getAuthenticationRequest(), inResponseTo)); String issuer = response.getIssuer().getValue(); String destination = response.getDestination(); String location = token.getRelyingPartyRegistration().getAssertionConsumerServiceLocation(); if (StringUtils.hasText(destination) && !destination.equals(location)) { String message = "Invalid destination [" + destination + "] for SAML response [" + response.getID() + "]"; result = result.concat(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, message)); } String assertingPartyEntityId = token.getRelyingPartyRegistration().getAssertingPartyDetails() .getEntityId(); if (!StringUtils.hasText(issuer) || !issuer.equals(assertingPartyEntityId)) { String message = String.format("Invalid issuer [%s] for SAML response [%s]", issuer, response.getID()); result = result.concat(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, message)); } if (response.getAssertions().isEmpty()) { result = result.concat( new Saml2Error(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, "No assertions found in response.")); } return result; }; } private static Saml2ResponseValidatorResult validateInResponseTo(AbstractSaml2AuthenticationRequest storedRequest, String inResponseTo) { if (!StringUtils.hasText(inResponseTo)) { return Saml2ResponseValidatorResult.success(); } if (storedRequest == null) { String message = "The response contained an InResponseTo attribute [" + inResponseTo + "]" + " but no saved authentication request was found"; return Saml2ResponseValidatorResult .failure(new Saml2Error(Saml2ErrorCodes.INVALID_IN_RESPONSE_TO, message)); } if (!inResponseTo.equals(storedRequest.getId())) { String message = "The InResponseTo attribute [" + inResponseTo + "] does not match the ID of the " + "authentication request [" + storedRequest.getId() + "]"; return Saml2ResponseValidatorResult .failure(new Saml2Error(Saml2ErrorCodes.INVALID_IN_RESPONSE_TO, message)); } return Saml2ResponseValidatorResult.success(); } /** * Construct a default strategy for validating each SAML 2.0 Assertion and associated * {@link Authentication} token * @return the default assertion validator strategy */ public static Converter<AssertionToken, Saml2ResponseValidatorResult> createDefaultAssertionValidator() { return createDefaultAssertionValidatorWithParameters( (params) -> params.put(SAML2AssertionValidationParameters.CLOCK_SKEW, Duration.ofMinutes(5))); } /** * Construct a default strategy for validating each SAML 2.0 Assertion and associated * {@link Authentication} token * @param contextConverter the conversion strategy to use to generate a * {@link ValidationContext} for each assertion being validated * @return the default assertion validator strategy * @deprecated Use {@link #createDefaultAssertionValidatorWithParameters} instead */ @Deprecated public static Converter<AssertionToken, Saml2ResponseValidatorResult> createDefaultAssertionValidator( Converter<AssertionToken, ValidationContext> contextConverter) { return createAssertionValidator(Saml2ErrorCodes.INVALID_ASSERTION, (assertionToken) -> SAML20AssertionValidators.attributeValidator, contextConverter); } /** * Construct a default strategy for validating each SAML 2.0 Assertion and associated * {@link Authentication} token * @param validationContextParameters a consumer for editing the values passed to the * {@link ValidationContext} for each assertion being validated * @return the default assertion validator strategy * @since 5.8 */ public static Converter<AssertionToken, Saml2ResponseValidatorResult> createDefaultAssertionValidatorWithParameters( Consumer<Map<String, Object>> validationContextParameters) { return createAssertionValidator(Saml2ErrorCodes.INVALID_ASSERTION, (assertionToken) -> SAML20AssertionValidators.attributeValidator, (assertionToken) -> createValidationContext(assertionToken, validationContextParameters)); } /** * Construct a default strategy for converting a SAML 2.0 Response and * {@link Authentication} token into a {@link Saml2Authentication} * @return the default response authentication converter strategy */ public static Converter<ResponseToken, Saml2Authentication> createDefaultResponseAuthenticationConverter() { return (responseToken) -> { Response response = responseToken.response; Saml2AuthenticationToken token = responseToken.token; Assertion assertion = CollectionUtils.firstElement(response.getAssertions()); String username = assertion.getSubject().getNameID().getValue(); Map<String, List<Object>> attributes = getAssertionAttributes(assertion); List<String> sessionIndexes = getSessionIndexes(assertion); DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal(username, attributes, sessionIndexes); String registrationId = responseToken.token.getRelyingPartyRegistration().getRegistrationId(); principal.setRelyingPartyRegistrationId(registrationId); return new Saml2Authentication(principal, token.getSaml2Response(), AuthorityUtils.createAuthorityList("ROLE_USER")); }; } /** * @param authentication the authentication request object, must be of type * {@link Saml2AuthenticationToken} * @return {@link Saml2Authentication} if the assertion is valid * @throws AuthenticationException if a validation exception occurs */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { try { Saml2AuthenticationToken token = (Saml2AuthenticationToken) authentication; String serializedResponse = token.getSaml2Response(); Response response = parseResponse(serializedResponse); process(token, response); AbstractAuthenticationToken authenticationResponse = this.responseAuthenticationConverter .convert(new ResponseToken(response, token)); if (authenticationResponse != null) { authenticationResponse.setDetails(authentication.getDetails()); } return authenticationResponse; } catch (Saml2AuthenticationException ex) { throw ex; } catch (Exception ex) { throw createAuthenticationException(Saml2ErrorCodes.INTERNAL_VALIDATION_ERROR, ex.getMessage(), ex); } } @Override public boolean supports(Class<?> authentication) { return authentication != null && Saml2AuthenticationToken.class.isAssignableFrom(authentication); } private Response parseResponse(String response) throws Saml2Exception, Saml2AuthenticationException { try { Document document = this.parserPool .parse(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (Response) this.responseUnmarshaller.unmarshall(element); } catch (Exception ex) { throw createAuthenticationException(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, ex.getMessage(), ex); } } private void process(Saml2AuthenticationToken token, Response response) { String issuer = response.getIssuer().getValue(); this.logger.debug(LogMessage.format("Processing SAML response from %s", issuer)); boolean responseSigned = response.isSigned(); ResponseToken responseToken = new ResponseToken(response, token); Saml2ResponseValidatorResult result = this.responseSignatureValidator.convert(responseToken); if (responseSigned) { this.responseElementsDecrypter.accept(responseToken); } else if (!response.getEncryptedAssertions().isEmpty()) { result = result.concat(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Did not decrypt response [" + response.getID() + "] since it is not signed")); } result = result.concat(this.responseValidator.convert(responseToken)); boolean allAssertionsSigned = true; for (Assertion assertion : response.getAssertions()) { AssertionToken assertionToken = new AssertionToken(assertion, token); result = result.concat(this.assertionSignatureValidator.convert(assertionToken)); allAssertionsSigned = allAssertionsSigned && assertion.isSigned(); if (responseSigned || assertion.isSigned()) { this.assertionElementsDecrypter.accept(new AssertionToken(assertion, token)); } result = result.concat(this.assertionValidator.convert(assertionToken)); } if (!responseSigned && !allAssertionsSigned) { String description = "Either the response or one of the assertions is unsigned. " + "Please either sign the response or all of the assertions."; result = result.concat(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, description)); } Assertion firstAssertion = CollectionUtils.firstElement(response.getAssertions()); if (firstAssertion != null && !hasName(firstAssertion)) { Saml2Error error = new Saml2Error(Saml2ErrorCodes.SUBJECT_NOT_FOUND, "Assertion [" + firstAssertion.getID() + "] is missing a subject"); result = result.concat(error); } if (result.hasErrors()) { Collection<Saml2Error> errors = result.getErrors(); if (this.logger.isTraceEnabled()) { this.logger.debug("Found " + errors.size() + " validation errors in SAML response [" + response.getID() + "]: " + errors); } else if (this.logger.isDebugEnabled()) { this.logger.debug( "Found " + errors.size() + " validation errors in SAML response [" + response.getID() + "]"); } Saml2Error first = errors.iterator().next(); throw createAuthenticationException(first.getErrorCode(), first.getDescription(), null); } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Successfully processed SAML Response [" + response.getID() + "]"); } } } private Converter<ResponseToken, Saml2ResponseValidatorResult> createDefaultResponseSignatureValidator() { return (responseToken) -> { Response response = responseToken.getResponse(); RelyingPartyRegistration registration = responseToken.getToken().getRelyingPartyRegistration(); if (response.isSigned()) { return OpenSamlVerificationUtils.verifySignature(response, registration).post(response.getSignature()); } return Saml2ResponseValidatorResult.success(); }; } private Consumer<ResponseToken> createDefaultResponseElementsDecrypter() { return (responseToken) -> { Response response = responseToken.getResponse(); RelyingPartyRegistration registration = responseToken.getToken().getRelyingPartyRegistration(); try { OpenSamlDecryptionUtils.decryptResponseElements(response, registration); } catch (Exception ex) { throw createAuthenticationException(Saml2ErrorCodes.DECRYPTION_ERROR, ex.getMessage(), ex); } }; } private static String getStatusCode(Response response) { if (response.getStatus() == null) { return StatusCode.SUCCESS; } if (response.getStatus().getStatusCode() == null) { return StatusCode.SUCCESS; } return response.getStatus().getStatusCode().getValue(); } private Converter<AssertionToken, Saml2ResponseValidatorResult> createDefaultAssertionSignatureValidator() { return createAssertionValidator(Saml2ErrorCodes.INVALID_SIGNATURE, (assertionToken) -> { RelyingPartyRegistration registration = assertionToken.getToken().getRelyingPartyRegistration(); SignatureTrustEngine engine = OpenSamlVerificationUtils.trustEngine(registration); return SAML20AssertionValidators.createSignatureValidator(engine); }, (assertionToken) -> new ValidationContext( Collections.singletonMap(SAML2AssertionValidationParameters.SIGNATURE_REQUIRED, false))); } private Consumer<AssertionToken> createDefaultAssertionElementsDecrypter() { return (assertionToken) -> { Assertion assertion = assertionToken.getAssertion(); RelyingPartyRegistration registration = assertionToken.getToken().getRelyingPartyRegistration(); try { OpenSamlDecryptionUtils.decryptAssertionElements(assertion, registration); } catch (Exception ex) { throw createAuthenticationException(Saml2ErrorCodes.DECRYPTION_ERROR, ex.getMessage(), ex); } }; } private boolean hasName(Assertion assertion) { if (assertion == null) { return false; } if (assertion.getSubject() == null) { return false; } if (assertion.getSubject().getNameID() == null) { return false; } return assertion.getSubject().getNameID().getValue() != null; } private static Map<String, List<Object>> getAssertionAttributes(Assertion assertion) { MultiValueMap<String, Object> attributeMap = new LinkedMultiValueMap<>(); for (AttributeStatement attributeStatement : assertion.getAttributeStatements()) { for (Attribute attribute : attributeStatement.getAttributes()) { List<Object> attributeValues = new ArrayList<>(); for (XMLObject xmlObject : attribute.getAttributeValues()) { Object attributeValue = getXmlObjectValue(xmlObject); if (attributeValue != null) { attributeValues.add(attributeValue); } } attributeMap.addAll(attribute.getName(), attributeValues); } } return new LinkedHashMap<>(attributeMap); // gh-11785 } private static List<String> getSessionIndexes(Assertion assertion) { List<String> sessionIndexes = new ArrayList<>(); for (AuthnStatement statement : assertion.getAuthnStatements()) { sessionIndexes.add(statement.getSessionIndex()); } return sessionIndexes; } private static Object getXmlObjectValue(XMLObject xmlObject) { if (xmlObject instanceof XSAny) { return ((XSAny) xmlObject).getTextContent(); } if (xmlObject instanceof XSString) { return ((XSString) xmlObject).getValue(); } if (xmlObject instanceof XSInteger) { return ((XSInteger) xmlObject).getValue(); } if (xmlObject instanceof XSURI) { return ((XSURI) xmlObject).getURI(); } if (xmlObject instanceof XSBoolean) { XSBooleanValue xsBooleanValue = ((XSBoolean) xmlObject).getValue(); return (xsBooleanValue != null) ? xsBooleanValue.getValue() : null; } if (xmlObject instanceof XSDateTime) { return ((XSDateTime) xmlObject).getValue(); } return xmlObject; } private static Saml2AuthenticationException createAuthenticationException(String code, String message, Exception cause) { return new Saml2AuthenticationException(new Saml2Error(code, message), cause); } private static Converter<AssertionToken, Saml2ResponseValidatorResult> createAssertionValidator(String errorCode, Converter<AssertionToken, SAML20AssertionValidator> validatorConverter, Converter<AssertionToken, ValidationContext> contextConverter) { return (assertionToken) -> { Assertion assertion = assertionToken.assertion; SAML20AssertionValidator validator = validatorConverter.convert(assertionToken); ValidationContext context = contextConverter.convert(assertionToken); try { ValidationResult result = validator.validate(assertion, context); if (result == ValidationResult.VALID) { return Saml2ResponseValidatorResult.success(); } } catch (Exception ex) { String message = String.format("Invalid assertion [%s] for SAML response [%s]: %s", assertion.getID(), ((Response) assertion.getParent()).getID(), ex.getMessage()); return Saml2ResponseValidatorResult.failure(new Saml2Error(errorCode, message)); } String message = String.format("Invalid assertion [%s] for SAML response [%s]: %s", assertion.getID(), ((Response) assertion.getParent()).getID(), context.getValidationFailureMessage()); return Saml2ResponseValidatorResult.failure(new Saml2Error(errorCode, message)); }; } private static ValidationContext createValidationContext(AssertionToken assertionToken, Consumer<Map<String, Object>> paramsConsumer) { Saml2AuthenticationToken token = assertionToken.token; RelyingPartyRegistration relyingPartyRegistration = token.getRelyingPartyRegistration(); String audience = relyingPartyRegistration.getEntityId(); String recipient = relyingPartyRegistration.getAssertionConsumerServiceLocation(); String assertingPartyEntityId = relyingPartyRegistration.getAssertingPartyDetails().getEntityId(); Map<String, Object> params = new HashMap<>(); Assertion assertion = assertionToken.getAssertion(); if (assertionContainsInResponseTo(assertion)) { String requestId = getAuthnRequestId(token.getAuthenticationRequest()); params.put(SAML2AssertionValidationParameters.SC_VALID_IN_RESPONSE_TO, requestId); } params.put(SAML2AssertionValidationParameters.COND_VALID_AUDIENCES, Collections.singleton(audience)); params.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton(recipient)); params.put(SAML2AssertionValidationParameters.VALID_ISSUERS, Collections.singleton(assertingPartyEntityId)); paramsConsumer.accept(params); return new ValidationContext(params); } private static boolean assertionContainsInResponseTo(Assertion assertion) { if (assertion.getSubject() == null) { return false; } for (SubjectConfirmation confirmation : assertion.getSubject().getSubjectConfirmations()) { SubjectConfirmationData confirmationData = confirmation.getSubjectConfirmationData(); if (confirmationData == null) { continue; } if (StringUtils.hasText(confirmationData.getInResponseTo())) { return true; } } return false; } private static String getAuthnRequestId(AbstractSaml2AuthenticationRequest serialized) { return (serialized != null) ? serialized.getId() : null; } private static class SAML20AssertionValidators { private static final Collection<ConditionValidator> conditions = new ArrayList<>(); private static final Collection<SubjectConfirmationValidator> subjects = new ArrayList<>(); private static final Collection<StatementValidator> statements = new ArrayList<>(); private static final SignaturePrevalidator validator = new SAMLSignatureProfileValidator(); static { conditions.add(new AudienceRestrictionConditionValidator()); conditions.add(new DelegationRestrictionConditionValidator()); conditions.add(new ConditionValidator() { @Nonnull @Override public QName getServicedCondition() { return OneTimeUse.DEFAULT_ELEMENT_NAME; } @Nonnull @Override public ValidationResult validate(Condition condition, Assertion assertion, ValidationContext context) { // applications should validate their own OneTimeUse conditions return ValidationResult.VALID; } }); subjects.add(new BearerSubjectConfirmationValidator() { @Override protected ValidationResult validateAddress(SubjectConfirmation confirmation, Assertion assertion, ValidationContext context, boolean required) { // applications should validate their own addresses - gh-7514 return ValidationResult.VALID; } }); } private static final SAML20AssertionValidator attributeValidator = new SAML20AssertionValidator(conditions, subjects, statements, null, null, null) { @Nonnull @Override protected ValidationResult validateSignature(Assertion token, ValidationContext context) { return ValidationResult.VALID; } }; static SAML20AssertionValidator createSignatureValidator(SignatureTrustEngine engine) { return new SAML20AssertionValidator(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null, engine, validator) { @Nonnull @Override protected ValidationResult validateConditions(Assertion assertion, ValidationContext context) { return ValidationResult.VALID; } @Nonnull @Override protected ValidationResult validateSubjectConfirmation(Assertion assertion, ValidationContext context) { return ValidationResult.VALID; } @Nonnull @Override protected ValidationResult validateStatements(Assertion assertion, ValidationContext context) { return ValidationResult.VALID; } @Override protected ValidationResult validateIssuer(Assertion assertion, ValidationContext context) { return ValidationResult.VALID; } }; } } /** * A tuple containing an OpenSAML {@link Response} and its associated authentication * token. * * @since 5.4 */ public static class ResponseToken { private final Saml2AuthenticationToken token; private final Response response; ResponseToken(Response response, Saml2AuthenticationToken token) { this.token = token; this.response = response; } public Response getResponse() { return this.response; } public Saml2AuthenticationToken getToken() { return this.token; } } /** * A tuple containing an OpenSAML {@link Assertion} and its associated authentication * token. * * @since 5.4 */ public static class AssertionToken { private final Saml2AuthenticationToken token; private final Assertion assertion; AssertionToken(Assertion assertion, Saml2AuthenticationToken token) { this.token = token; this.assertion = assertion; } public Assertion getAssertion() { return this.assertion; } public Saml2AuthenticationToken getToken() { return this.token; } } }
38,023
40.738749
154
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Authentication.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.saml2.provider.service.authentication; import java.util.Collection; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.util.Assert; /** * An implementation of an {@link AbstractAuthenticationToken} that represents an * authenticated SAML 2.0 {@link Authentication}. * <p> * The {@link Authentication} associates valid SAML assertion data with a Spring Security * authentication object The complete assertion is contained in the object in String * format, {@link Saml2Authentication#getSaml2Response()} * * @since 5.2 * @see AbstractAuthenticationToken */ public class Saml2Authentication extends AbstractAuthenticationToken { private final AuthenticatedPrincipal principal; private final String saml2Response; /** * Construct a {@link Saml2Authentication} using the provided parameters * @param principal the logged in user * @param saml2Response the SAML 2.0 response used to authenticate the user * @param authorities the authorities for the logged in user */ public Saml2Authentication(AuthenticatedPrincipal principal, String saml2Response, Collection<? extends GrantedAuthority> authorities) { super(authorities); Assert.notNull(principal, "principal cannot be null"); Assert.hasText(saml2Response, "saml2Response cannot be null"); this.principal = principal; this.saml2Response = saml2Response; setAuthenticated(true); } @Override public Object getPrincipal() { return this.principal; } /** * Returns the SAML response object, as decoded XML. May contain encrypted elements * @return string representation of the SAML Response XML object */ public String getSaml2Response() { return this.saml2Response; } @Override public Object getCredentials() { return getSaml2Response(); } }
2,653
32.594937
89
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlVerificationUtils.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.saml2.provider.service.authentication; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import org.opensaml.core.criterion.EntityIdCriterion; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.criterion.ProtocolCriterion; import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.RequestAbstractType; import org.opensaml.saml.saml2.core.StatusResponseType; import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialResolver; import org.opensaml.security.credential.UsageType; import org.opensaml.security.credential.criteria.impl.EvaluableEntityIDCredentialCriterion; import org.opensaml.security.credential.criteria.impl.EvaluableUsageCredentialCriterion; import org.opensaml.security.credential.impl.CollectionCredentialResolver; import org.opensaml.security.criteria.UsageCriterion; import org.opensaml.security.x509.BasicX509Credential; import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap; import org.opensaml.xmlsec.signature.Signature; import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.Saml2ResponseValidatorResult; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.web.util.UriUtils; /** * Utility methods for verifying SAML component signatures with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlVerificationUtils { static VerifierPartial verifySignature(StatusResponseType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } static VerifierPartial verifySignature(RequestAbstractType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } static SignatureTrustEngine trustEngine(RelyingPartyRegistration registration) { Set<Credential> credentials = new HashSet<>(); Collection<Saml2X509Credential> keys = registration.getAssertingPartyDetails().getVerificationX509Credentials(); for (Saml2X509Credential key : keys) { BasicX509Credential cred = new BasicX509Credential(key.getCertificate()); cred.setUsageType(UsageType.SIGNING); cred.setEntityId(registration.getAssertingPartyDetails().getEntityId()); credentials.add(cred); } CredentialResolver credentialsResolver = new CollectionCredentialResolver(credentials); return new ExplicitKeySignatureTrustEngine(credentialsResolver, DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver()); } private OpenSamlVerificationUtils() { } static class VerifierPartial { private final String id; private final CriteriaSet criteria; private final SignatureTrustEngine trustEngine; VerifierPartial(StatusResponseType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } VerifierPartial(RequestAbstractType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } Saml2ResponseValidatorResult redirect(HttpServletRequest request, String objectParameterName) { RedirectSignature signature = new RedirectSignature(request, objectParameterName); if (signature.getAlgorithm() == null) { return Saml2ResponseValidatorResult.failure(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature algorithm for object [" + this.id + "]")); } if (!signature.hasSignature()) { return Saml2ResponseValidatorResult.failure(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature for object [" + this.id + "]")); } Collection<Saml2Error> errors = new ArrayList<>(); String algorithmUri = signature.getAlgorithm(); try { if (!this.trustEngine.validate(signature.getSignature(), signature.getContent(), algorithmUri, this.criteria, null)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return Saml2ResponseValidatorResult.failure(errors); } Saml2ResponseValidatorResult post(Signature signature) { Collection<Saml2Error> errors = new ArrayList<>(); SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(signature); } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } try { if (!this.trustEngine.validate(signature, this.criteria)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return Saml2ResponseValidatorResult.failure(errors); } private CriteriaSet verificationCriteria(Issuer issuer) { CriteriaSet criteria = new CriteriaSet(); criteria.add(new EvaluableEntityIDCredentialCriterion(new EntityIdCriterion(issuer.getValue()))); criteria.add(new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS))); criteria.add(new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); return criteria; } private static class RedirectSignature { private final HttpServletRequest request; private final String objectParameterName; RedirectSignature(HttpServletRequest request, String objectParameterName) { this.request = request; this.objectParameterName = objectParameterName; } String getAlgorithm() { return this.request.getParameter(Saml2ParameterNames.SIG_ALG); } byte[] getContent() { if (this.request.getParameter(Saml2ParameterNames.RELAY_STATE) != null) { return String .format("%s=%s&%s=%s&%s=%s", this.objectParameterName, UriUtils.encode(this.request.getParameter(this.objectParameterName), StandardCharsets.ISO_8859_1), Saml2ParameterNames.RELAY_STATE, UriUtils.encode(this.request.getParameter(Saml2ParameterNames.RELAY_STATE), StandardCharsets.ISO_8859_1), Saml2ParameterNames.SIG_ALG, UriUtils.encode(getAlgorithm(), StandardCharsets.ISO_8859_1)) .getBytes(StandardCharsets.UTF_8); } else { return String .format("%s=%s&%s=%s", this.objectParameterName, UriUtils.encode(this.request.getParameter(this.objectParameterName), StandardCharsets.ISO_8859_1), Saml2ParameterNames.SIG_ALG, UriUtils.encode(getAlgorithm(), StandardCharsets.ISO_8859_1)) .getBytes(StandardCharsets.UTF_8); } } byte[] getSignature() { return Saml2Utils.samlDecode(this.request.getParameter(Saml2ParameterNames.SIGNATURE)); } boolean hasSignature() { return this.request.getParameter(Saml2ParameterNames.SIGNATURE) != null; } } } }
8,769
38.327354
114
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationException.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.saml2.provider.service.authentication; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.util.Assert; /** * This exception is thrown for all SAML 2.0 related {@link Authentication} errors. * * <p> * There are a number of scenarios where an error may occur, for example: * <ul> * <li>The response or assertion request is missing or malformed</li> * <li>Missing or invalid subject</li> * <li>Missing or invalid signatures</li> * <li>The time period validation for the assertion fails</li> * <li>One of the assertion conditions was not met</li> * <li>Decryption failed</li> * <li>Unable to locate a subject identifier, commonly known as username</li> * </ul> * * @since 5.2 */ public class Saml2AuthenticationException extends AuthenticationException { private final Saml2Error error; /** * Constructs a {@code Saml2AuthenticationException} using the provided parameters. * @param error the {@link Saml2Error SAML 2.0 Error} */ public Saml2AuthenticationException(Saml2Error error) { this(error, error.getDescription()); } /** * Constructs a {@code Saml2AuthenticationException} using the provided parameters. * @param error the {@link Saml2Error SAML 2.0 Error} * @param cause the root cause */ public Saml2AuthenticationException(Saml2Error error, Throwable cause) { this(error, (cause != null) ? cause.getMessage() : error.getDescription(), cause); } /** * Constructs a {@code Saml2AuthenticationException} using the provided parameters. * @param error the {@link Saml2Error SAML 2.0 Error} * @param message the detail message */ public Saml2AuthenticationException(Saml2Error error, String message) { this(error, message, null); } /** * Constructs a {@code Saml2AuthenticationException} using the provided parameters. * @param error the {@link Saml2Error SAML 2.0 Error} * @param message the detail message * @param cause the root cause */ public Saml2AuthenticationException(Saml2Error error, String message, Throwable cause) { super(message, cause); Assert.notNull(error, "error cannot be null"); this.error = error; } /** * Get the associated {@link Saml2Error} * @return the associated {@link Saml2Error} */ public Saml2Error getSaml2Error() { return this.error; } @Override public String toString() { final StringBuffer sb = new StringBuffer("Saml2AuthenticationException{"); sb.append("error=").append(this.error); sb.append('}'); return sb.toString(); } }
3,288
31.89
89
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationToken.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.saml2.provider.service.authentication; import java.util.Collections; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.web.authentication.Saml2WebSsoAuthenticationFilter; import org.springframework.util.Assert; /** * Represents an incoming SAML 2.0 response containing an assertion that has not been * validated. {@link Saml2AuthenticationToken#isAuthenticated()} will always return false. * * @author Filip Hanik * @author Josh Cummings * @since 5.2 */ public class Saml2AuthenticationToken extends AbstractAuthenticationToken { private final RelyingPartyRegistration relyingPartyRegistration; private final String saml2Response; private final AbstractSaml2AuthenticationRequest authenticationRequest; /** * Creates a {@link Saml2AuthenticationToken} with the provided parameters. * * Note that the given {@link RelyingPartyRegistration} should have all its templates * resolved at this point. See {@link Saml2WebSsoAuthenticationFilter} for an example * of performing that resolution. * @param relyingPartyRegistration the resolved {@link RelyingPartyRegistration} to * use * @param saml2Response the SAML 2.0 response to authenticate * @param authenticationRequest the {@code AuthNRequest} sent to the asserting party * * @since 5.6 */ public Saml2AuthenticationToken(RelyingPartyRegistration relyingPartyRegistration, String saml2Response, AbstractSaml2AuthenticationRequest authenticationRequest) { super(Collections.emptyList()); Assert.notNull(relyingPartyRegistration, "relyingPartyRegistration cannot be null"); Assert.notNull(saml2Response, "saml2Response cannot be null"); this.relyingPartyRegistration = relyingPartyRegistration; this.saml2Response = saml2Response; this.authenticationRequest = authenticationRequest; } /** * Creates a {@link Saml2AuthenticationToken} with the provided parameters * * Note that the given {@link RelyingPartyRegistration} should have all its templates * resolved at this point. See {@link Saml2WebSsoAuthenticationFilter} for an example * of performing that resolution. * @param relyingPartyRegistration the resolved {@link RelyingPartyRegistration} to * use * @param saml2Response the SAML 2.0 response to authenticate * * @since 5.4 */ public Saml2AuthenticationToken(RelyingPartyRegistration relyingPartyRegistration, String saml2Response) { this(relyingPartyRegistration, saml2Response, null); } /** * Returns the decoded and inflated SAML 2.0 Response XML object as a string * @return decoded and inflated XML data as a {@link String} */ @Override public Object getCredentials() { return getSaml2Response(); } /** * Always returns null. * @return null */ @Override public Object getPrincipal() { return null; } /** * Get the resolved {@link RelyingPartyRegistration} associated with the request * @return the resolved {@link RelyingPartyRegistration} * @since 5.4 */ public RelyingPartyRegistration getRelyingPartyRegistration() { return this.relyingPartyRegistration; } /** * Returns inflated and decoded XML representation of the SAML 2 Response * @return inflated and decoded XML representation of the SAML 2 Response */ public String getSaml2Response() { return this.saml2Response; } /** * @return false */ @Override public boolean isAuthenticated() { return false; } /** * The state of this object cannot be changed. Will always throw an exception * @param authenticated ignored */ @Override public void setAuthenticated(boolean authenticated) { throw new IllegalArgumentException(); } /** * Returns the authentication request sent to the assertion party or {@code null} if * no authentication request is present * @return the authentication request sent to the assertion party * @since 5.6 */ public AbstractSaml2AuthenticationRequest getAuthenticationRequest() { return this.authenticationRequest; } }
4,786
32.243056
110
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipal.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.saml2.provider.service.authentication; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import org.springframework.util.Assert; /** * Default implementation of a {@link Saml2AuthenticatedPrincipal}. * * @author Clement Stoquart * @since 5.4 */ public class DefaultSaml2AuthenticatedPrincipal implements Saml2AuthenticatedPrincipal, Serializable { private final String name; private final Map<String, List<Object>> attributes; private final List<String> sessionIndexes; private String registrationId; public DefaultSaml2AuthenticatedPrincipal(String name, Map<String, List<Object>> attributes) { this(name, attributes, Collections.emptyList()); } public DefaultSaml2AuthenticatedPrincipal(String name, Map<String, List<Object>> attributes, List<String> sessionIndexes) { Assert.notNull(name, "name cannot be null"); Assert.notNull(attributes, "attributes cannot be null"); Assert.notNull(sessionIndexes, "sessionIndexes cannot be null"); this.name = name; this.attributes = attributes; this.sessionIndexes = sessionIndexes; } @Override public String getName() { return this.name; } @Override public Map<String, List<Object>> getAttributes() { return this.attributes; } @Override public List<String> getSessionIndexes() { return this.sessionIndexes; } @Override public String getRelyingPartyRegistrationId() { return this.registrationId; } public void setRelyingPartyRegistrationId(String registrationId) { Assert.notNull(registrationId, "relyingPartyRegistrationId cannot be null"); this.registrationId = registrationId; } }
2,310
27.182927
102
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlDecryptionUtils.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.saml2.provider.service.authentication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.opensaml.saml.saml2.core.Assertion; import org.opensaml.saml.saml2.core.Attribute; import org.opensaml.saml.saml2.core.AttributeStatement; import org.opensaml.saml.saml2.core.EncryptedAssertion; import org.opensaml.saml.saml2.core.EncryptedAttribute; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.Response; import org.opensaml.saml.saml2.encryption.Decrypter; import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; import org.opensaml.xmlsec.keyinfo.impl.CollectionKeyInfoCredentialResolver; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * Utility methods for decrypting SAML components with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlDecryptionUtils { private static final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver( Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), new SimpleRetrievalMethodEncryptedKeyResolver())); static void decryptResponseElements(Response response, RelyingPartyRegistration registration) { Decrypter decrypter = decrypter(registration); for (EncryptedAssertion encryptedAssertion : response.getEncryptedAssertions()) { try { Assertion assertion = decrypter.decrypt(encryptedAssertion); response.getAssertions().add(assertion); } catch (Exception ex) { throw new Saml2Exception(ex); } } } static void decryptAssertionElements(Assertion assertion, RelyingPartyRegistration registration) { Decrypter decrypter = decrypter(registration); for (AttributeStatement statement : assertion.getAttributeStatements()) { for (EncryptedAttribute encryptedAttribute : statement.getEncryptedAttributes()) { try { Attribute attribute = decrypter.decrypt(encryptedAttribute); statement.getAttributes().add(attribute); } catch (Exception ex) { throw new Saml2Exception(ex); } } } if (assertion.getSubject() == null) { return; } if (assertion.getSubject().getEncryptedID() == null) { return; } try { assertion.getSubject().setNameID((NameID) decrypter.decrypt(assertion.getSubject().getEncryptedID())); } catch (Exception ex) { throw new Saml2Exception(ex); } } private static Decrypter decrypter(RelyingPartyRegistration registration) { Collection<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential key : registration.getDecryptionX509Credentials()) { Credential cred = CredentialSupport.getSimpleCredential(key.getCertificate(), key.getPrivateKey()); credentials.add(cred); } KeyInfoCredentialResolver resolver = new CollectionKeyInfoCredentialResolver(credentials); Decrypter decrypter = new Decrypter(null, resolver, encryptedKeyResolver); decrypter.setRootInNewDocument(true); return decrypter; } private OpenSamlDecryptionUtils() { } }
4,359
37.245614
105
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/AbstractSaml2AuthenticationRequest.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.saml2.provider.service.authentication; import java.io.Serializable; import java.nio.charset.Charset; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.util.Assert; /** * Data holder for {@code AuthNRequest} parameters to be sent using either the * {@link Saml2MessageBinding#POST} or {@link Saml2MessageBinding#REDIRECT} binding. Data * will be encoded and possibly deflated, but will not be escaped for transport, ie URL * encoded, {@link org.springframework.web.util.UriUtils#encode(String, Charset)} or HTML * encoded, {@link org.springframework.web.util.HtmlUtils#htmlEscape(String)}. * https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf * (line 2031) * * @since 5.3 * @see Saml2PostAuthenticationRequest * @see Saml2RedirectAuthenticationRequest */ public abstract class AbstractSaml2AuthenticationRequest implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String samlRequest; private final String relayState; private final String authenticationRequestUri; private final String relyingPartyRegistrationId; private final String id; /** * Mandatory constructor for the {@link AbstractSaml2AuthenticationRequest} * @param samlRequest - the SAMLRequest XML data, SAML encoded, cannot be empty or * null * @param relayState - RelayState value that accompanies the request, may be null * @param authenticationRequestUri - The authenticationRequestUri, a URL, where to * send the XML message, cannot be empty or null * @param relyingPartyRegistrationId the registration id of the relying party, may be * null * @param id This is the unique id used in the {@link #samlRequest}, cannot be empty * or null */ AbstractSaml2AuthenticationRequest(String samlRequest, String relayState, String authenticationRequestUri, String relyingPartyRegistrationId, String id) { Assert.hasText(samlRequest, "samlRequest cannot be null or empty"); Assert.hasText(authenticationRequestUri, "authenticationRequestUri cannot be null or empty"); this.authenticationRequestUri = authenticationRequestUri; this.samlRequest = samlRequest; this.relayState = relayState; this.relyingPartyRegistrationId = relyingPartyRegistrationId; this.id = id; } /** * Returns the AuthNRequest XML value to be sent. This value is already encoded for * transport. If {@link #getBinding()} is {@link Saml2MessageBinding#REDIRECT} the * value is deflated and SAML encoded. If {@link #getBinding()} is * {@link Saml2MessageBinding#POST} the value is SAML encoded. * @return the SAMLRequest parameter value */ public String getSamlRequest() { return this.samlRequest; } /** * Returns the RelayState value, if present in the parameters * @return the RelayState value, or null if not available */ public String getRelayState() { return this.relayState; } /** * Returns the URI endpoint that this AuthNRequest should be sent to. * @return the URI endpoint for this message */ public String getAuthenticationRequestUri() { return this.authenticationRequestUri; } /** * The identifier for the {@link RelyingPartyRegistration} associated with this * request * @return the {@link RelyingPartyRegistration} id * @since 5.8 */ public String getRelyingPartyRegistrationId() { return this.relyingPartyRegistrationId; } /** * The unique identifier for this Authentication Request * @return the Authentication Request identifier * @since 5.8 */ public String getId() { return this.id; } /** * Returns the binding this AuthNRequest will be sent and encoded with. If * {@link Saml2MessageBinding#REDIRECT} is used, the DEFLATE encoding will be * automatically applied. * @return the binding this message will be sent with. */ public abstract Saml2MessageBinding getBinding(); /** * A builder for {@link AbstractSaml2AuthenticationRequest} and its subclasses. */ public static class Builder<T extends Builder<T>> { String authenticationRequestUri; String samlRequest; String relayState; String relyingPartyRegistrationId; String id; /** * @deprecated Use {@link #Builder(RelyingPartyRegistration)} instead */ @Deprecated protected Builder() { } /** * Creates a new Builder with relying party registration * @param registration the registration of the relying party. * @since 5.8 */ protected Builder(RelyingPartyRegistration registration) { this.relyingPartyRegistrationId = registration.getRegistrationId(); } /** * Casting the return as the generic subtype, when returning itself * @return this object */ @SuppressWarnings("unchecked") protected final T _this() { return (T) this; } /** * Sets the {@code RelayState} parameter that will accompany this AuthNRequest * @param relayState the relay state value, unencoded. if null or empty, the * parameter will be removed from the map. * @return this object */ public T relayState(String relayState) { this.relayState = relayState; return _this(); } /** * Sets the {@code SAMLRequest} parameter that will accompany this AuthNRequest * @param samlRequest the SAMLRequest parameter. * @return this object */ public T samlRequest(String samlRequest) { this.samlRequest = samlRequest; return _this(); } /** * Sets the {@code authenticationRequestUri}, a URL that will receive the * AuthNRequest message * @param authenticationRequestUri the relay state value, unencoded. * @return this object */ public T authenticationRequestUri(String authenticationRequestUri) { this.authenticationRequestUri = authenticationRequestUri; return _this(); } /** * This is the unique id used in the {@link #samlRequest} * @param id the SAML2 request id * @return the {@link AbstractSaml2AuthenticationRequest.Builder} for further * configurations * @since 5.8 */ public T id(String id) { Assert.notNull(id, "id cannot be null"); this.id = id; return _this(); } } }
7,003
30.981735
107
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequest.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.saml2.provider.service.authentication; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * Data holder for information required to send an {@code AuthNRequest} over a POST * binding from the service provider to the identity provider * https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf * (line 2031) * * @since 5.3 * @see org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver */ public class Saml2PostAuthenticationRequest extends AbstractSaml2AuthenticationRequest { Saml2PostAuthenticationRequest(String samlRequest, String relayState, String authenticationRequestUri, String relyingPartyRegistrationId, String id) { super(samlRequest, relayState, authenticationRequestUri, relyingPartyRegistrationId, id); } /** * @return {@link Saml2MessageBinding#POST} */ @Override public Saml2MessageBinding getBinding() { return Saml2MessageBinding.POST; } /** * Constructs a {@link Builder} from a {@link RelyingPartyRegistration} object. * @param registration a relying party registration * @return a modifiable builder object * @since 5.7 */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { String location = registration.getAssertingPartyDetails().getSingleSignOnServiceLocation(); return new Builder(registration).authenticationRequestUri(location); } /** * Builder class for a {@link Saml2PostAuthenticationRequest} object. */ public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> { private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Constructs an immutable {@link Saml2PostAuthenticationRequest} object. * @return an immutable {@link Saml2PostAuthenticationRequest} object. */ public Saml2PostAuthenticationRequest build() { return new Saml2PostAuthenticationRequest(this.samlRequest, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
2,891
36.076923
113
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticatedPrincipal.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.saml2.provider.service.authentication; import java.util.Collections; import java.util.List; import java.util.Map; import org.springframework.lang.Nullable; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.CollectionUtils; /** * Saml2 representation of an {@link AuthenticatedPrincipal}. * * @author Clement Stoquart * @since 5.2.2 */ public interface Saml2AuthenticatedPrincipal extends AuthenticatedPrincipal { /** * Get the first value of Saml2 token attribute by name * @param name the name of the attribute * @param <A> the type of the attribute * @return the first attribute value or {@code null} otherwise * @since 5.4 */ @Nullable default <A> A getFirstAttribute(String name) { List<A> values = getAttribute(name); return CollectionUtils.firstElement(values); } /** * Get the Saml2 token attribute by name * @param name the name of the attribute * @param <A> the type of the attribute * @return the attribute or {@code null} otherwise * @since 5.4 */ @Nullable default <A> List<A> getAttribute(String name) { return (List<A>) getAttributes().get(name); } /** * Get the Saml2 token attributes * @return the Saml2 token attributes * @since 5.4 */ default Map<String, List<Object>> getAttributes() { return Collections.emptyMap(); } /** * Get the {@link RelyingPartyRegistration} identifier * @return the {@link RelyingPartyRegistration} identifier * @since 5.6 */ default String getRelyingPartyRegistrationId() { return null; } default List<String> getSessionIndexes() { return Collections.emptyList(); } }
2,400
27.583333
97
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlLogoutRequestValidator.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.saml2.provider.service.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.function.Consumer; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.SAMLObject; import org.opensaml.saml.saml2.core.EncryptedID; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.impl.LogoutRequestUnmarshaller; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlVerificationUtils.VerifierPartial; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * A {@link Saml2LogoutRequestValidator} that authenticates a SAML 2.0 Logout Requests * received from a SAML 2.0 Asserting Party using OpenSAML. * * @author Josh Cummings * @since 5.6 */ public final class OpenSamlLogoutRequestValidator implements Saml2LogoutRequestValidator { static { OpenSamlInitializationService.initialize(); } private final ParserPool parserPool; private final LogoutRequestUnmarshaller unmarshaller; /** * Constructs a {@link OpenSamlLogoutRequestValidator} */ public OpenSamlLogoutRequestValidator() { XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); this.unmarshaller = (LogoutRequestUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() .getUnmarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); } /** * {@inheritDoc} */ @Override public Saml2LogoutValidatorResult validate(Saml2LogoutRequestValidatorParameters parameters) { Saml2LogoutRequest request = parameters.getLogoutRequest(); RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration(); Authentication authentication = parameters.getAuthentication(); byte[] b = Saml2Utils.samlDecode(request.getSamlRequest()); LogoutRequest logoutRequest = parse(inflateIfRequired(request, b)); return Saml2LogoutValidatorResult.withErrors().errors(verifySignature(request, logoutRequest, registration)) .errors(validateRequest(logoutRequest, registration, authentication)).build(); } private String inflateIfRequired(Saml2LogoutRequest request, byte[] b) { if (request.getBinding() == Saml2MessageBinding.REDIRECT) { return Saml2Utils.samlInflate(b); } return new String(b, StandardCharsets.UTF_8); } private LogoutRequest parse(String request) throws Saml2Exception { try { Document document = this.parserPool .parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutRequest) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception("Failed to deserialize LogoutRequest", ex); } } private Consumer<Collection<Saml2Error>> verifySignature(Saml2LogoutRequest request, LogoutRequest logoutRequest, RelyingPartyRegistration registration) { return (errors) -> { VerifierPartial partial = OpenSamlVerificationUtils.verifySignature(logoutRequest, registration); if (logoutRequest.isSigned()) { errors.addAll(partial.post(logoutRequest.getSignature())); } else { errors.addAll(partial.redirect(request)); } }; } private Consumer<Collection<Saml2Error>> validateRequest(LogoutRequest request, RelyingPartyRegistration registration, Authentication authentication) { return (errors) -> { validateIssuer(request, registration).accept(errors); validateDestination(request, registration).accept(errors); validateSubject(request, registration, authentication).accept(errors); }; } private Consumer<Collection<Saml2Error>> validateIssuer(LogoutRequest request, RelyingPartyRegistration registration) { return (errors) -> { if (request.getIssuer() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to find issuer in LogoutRequest")); return; } String issuer = request.getIssuer().getValue(); if (!issuer.equals(registration.getAssertingPartyDetails().getEntityId())) { errors.add( new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to match issuer to configured issuer")); } }; } private Consumer<Collection<Saml2Error>> validateDestination(LogoutRequest request, RelyingPartyRegistration registration) { return (errors) -> { if (request.getDestination() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to find destination in LogoutRequest")); return; } String destination = request.getDestination(); if (!destination.equals(registration.getSingleLogoutServiceLocation())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to match destination to configured destination")); } }; } private Consumer<Collection<Saml2Error>> validateSubject(LogoutRequest request, RelyingPartyRegistration registration, Authentication authentication) { return (errors) -> { if (authentication == null) { return; } NameID nameId = getNameId(request, registration); if (nameId == null) { errors.add( new Saml2Error(Saml2ErrorCodes.SUBJECT_NOT_FOUND, "Failed to find subject in LogoutRequest")); return; } validateNameId(nameId, authentication, errors); }; } private NameID getNameId(LogoutRequest request, RelyingPartyRegistration registration) { NameID nameId = request.getNameID(); if (nameId != null) { return nameId; } EncryptedID encryptedId = request.getEncryptedID(); if (encryptedId == null) { return null; } return decryptNameId(encryptedId, registration); } private void validateNameId(NameID nameId, Authentication authentication, Collection<Saml2Error> errors) { String name = nameId.getValue(); if (!name.equals(authentication.getName())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_REQUEST, "Failed to match subject in LogoutRequest with currently logged in user")); } } private NameID decryptNameId(EncryptedID encryptedId, RelyingPartyRegistration registration) { final SAMLObject decryptedId = LogoutRequestEncryptedIdUtils.decryptEncryptedId(encryptedId, registration); if (decryptedId instanceof NameID) { return ((NameID) decryptedId); } return null; } }
7,738
36.936275
123
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2Utils.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.saml2.provider.service.authentication.logout; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterOutputStream; import org.springframework.security.saml2.Saml2Exception; /** * Utility methods for working with serialized SAML messages. * * For internal use only. * * @author Josh Cummings */ final class Saml2Utils { private Saml2Utils() { } static String samlEncode(byte[] b) { return Base64.getEncoder().encodeToString(b); } static byte[] samlDecode(String s) { return Base64.getMimeDecoder().decode(s); } static byte[] samlDeflate(String s) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true)); deflater.write(s.getBytes(StandardCharsets.UTF_8)); deflater.finish(); return b.toByteArray(); } catch (IOException ex) { throw new Saml2Exception("Unable to deflate string", ex); } } static String samlInflate(byte[] b) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException ex) { throw new Saml2Exception("Unable to inflate string", ex); } } }
2,209
27.701299
102
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutResponseValidatorParameters.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.saml2.provider.service.authentication.logout; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * A holder of the parameters needed to invoke {@link Saml2LogoutResponseValidator} * * @author Josh Cummings * @since 5.6 */ public class Saml2LogoutResponseValidatorParameters { private final Saml2LogoutResponse response; private final Saml2LogoutRequest request; private final RelyingPartyRegistration registration; /** * Construct a {@link Saml2LogoutRequestValidatorParameters} * @param response the SAML 2.0 Logout Response received from the asserting party * @param request the SAML 2.0 Logout Request send by this application * @param registration the associated {@link RelyingPartyRegistration} */ public Saml2LogoutResponseValidatorParameters(Saml2LogoutResponse response, Saml2LogoutRequest request, RelyingPartyRegistration registration) { this.response = response; this.request = request; this.registration = registration; } /** * The SAML 2.0 Logout Response received from the asserting party * @return the logout response */ public Saml2LogoutResponse getLogoutResponse() { return this.response; } /** * The SAML 2.0 Logout Request sent by this application * @return the logout request */ public Saml2LogoutRequest getLogoutRequest() { return this.request; } /** * The {@link RelyingPartyRegistration} representing this relying party * @return the relying party */ public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } }
2,254
29.890411
104
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlLogoutResponseValidator.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.saml2.provider.service.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.function.Consumer; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.saml2.core.LogoutResponse; import org.opensaml.saml.saml2.core.StatusCode; import org.opensaml.saml.saml2.core.impl.LogoutResponseUnmarshaller; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlVerificationUtils.VerifierPartial; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * A {@link Saml2LogoutResponseValidator} that authenticates a SAML 2.0 Logout Responses * received from a SAML 2.0 Asserting Party using OpenSAML. * * @author Josh Cummings * @since 5.6 */ public class OpenSamlLogoutResponseValidator implements Saml2LogoutResponseValidator { static { OpenSamlInitializationService.initialize(); } private final ParserPool parserPool; private final LogoutResponseUnmarshaller unmarshaller; /** * Constructs a {@link OpenSamlLogoutRequestValidator} */ public OpenSamlLogoutResponseValidator() { XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); this.unmarshaller = (LogoutResponseUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() .getUnmarshaller(LogoutResponse.DEFAULT_ELEMENT_NAME); } /** * {@inheritDoc} */ @Override public Saml2LogoutValidatorResult validate(Saml2LogoutResponseValidatorParameters parameters) { Saml2LogoutResponse response = parameters.getLogoutResponse(); Saml2LogoutRequest request = parameters.getLogoutRequest(); RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration(); byte[] b = Saml2Utils.samlDecode(response.getSamlResponse()); LogoutResponse logoutResponse = parse(inflateIfRequired(response, b)); return Saml2LogoutValidatorResult.withErrors().errors(verifySignature(response, logoutResponse, registration)) .errors(validateRequest(logoutResponse, registration)) .errors(validateLogoutRequest(logoutResponse, request.getId())).build(); } private String inflateIfRequired(Saml2LogoutResponse response, byte[] b) { if (response.getBinding() == Saml2MessageBinding.REDIRECT) { return Saml2Utils.samlInflate(b); } return new String(b, StandardCharsets.UTF_8); } private LogoutResponse parse(String response) throws Saml2Exception { try { Document document = this.parserPool .parse(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutResponse) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception("Failed to deserialize LogoutResponse", ex); } } private Consumer<Collection<Saml2Error>> verifySignature(Saml2LogoutResponse response, LogoutResponse logoutResponse, RelyingPartyRegistration registration) { return (errors) -> { VerifierPartial partial = OpenSamlVerificationUtils.verifySignature(logoutResponse, registration); if (logoutResponse.isSigned()) { errors.addAll(partial.post(logoutResponse.getSignature())); } else { errors.addAll(partial.redirect(response)); } }; } private Consumer<Collection<Saml2Error>> validateRequest(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { validateIssuer(response, registration).accept(errors); validateDestination(response, registration).accept(errors); validateStatus(response).accept(errors); }; } private Consumer<Collection<Saml2Error>> validateIssuer(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { if (response.getIssuer() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to find issuer in LogoutResponse")); return; } String issuer = response.getIssuer().getValue(); if (!issuer.equals(registration.getAssertingPartyDetails().getEntityId())) { errors.add( new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to match issuer to configured issuer")); } }; } private Consumer<Collection<Saml2Error>> validateDestination(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { if (response.getDestination() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to find destination in LogoutResponse")); return; } String destination = response.getDestination(); if (!destination.equals(registration.getSingleLogoutServiceResponseLocation())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to match destination to configured destination")); } }; } private Consumer<Collection<Saml2Error>> validateStatus(LogoutResponse response) { return (errors) -> { if (response.getStatus() == null) { return; } if (response.getStatus().getStatusCode() == null) { return; } if (StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) { return; } if (StatusCode.PARTIAL_LOGOUT.equals(response.getStatus().getStatusCode().getValue())) { return; } errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Response indicated logout failed")); }; } private Consumer<Collection<Saml2Error>> validateLogoutRequest(LogoutResponse response, String id) { return (errors) -> { if (response.getInResponseTo() == null) { return; } if (response.getInResponseTo().equals(id)) { return; } errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "LogoutResponse InResponseTo doesn't match ID of associated LogoutRequest")); }; } }
7,117
36.861702
123
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/LogoutRequestEncryptedIdUtils.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.saml2.provider.service.authentication.logout; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.opensaml.saml.common.SAMLObject; import org.opensaml.saml.saml2.core.EncryptedID; import org.opensaml.saml.saml2.encryption.Decrypter; import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver; import org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; import org.opensaml.xmlsec.keyinfo.impl.CollectionKeyInfoCredentialResolver; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * Utility methods for decrypting EncryptedID from SAML logout request with OpenSAML * * For internal use only. * * this is mainly a adapted copy of OpenSamlDecryptionUtils * * @author Robert Stoiber */ final class LogoutRequestEncryptedIdUtils { private static final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver( Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), new SimpleRetrievalMethodEncryptedKeyResolver())); static SAMLObject decryptEncryptedId(EncryptedID encryptedId, RelyingPartyRegistration registration) { Decrypter decrypter = decrypter(registration); try { return decrypter.decrypt(encryptedId); } catch (Exception ex) { throw new Saml2Exception(ex); } } private static Decrypter decrypter(RelyingPartyRegistration registration) { Collection<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential key : registration.getDecryptionX509Credentials()) { Credential cred = CredentialSupport.getSimpleCredential(key.getCertificate(), key.getPrivateKey()); credentials.add(cred); } KeyInfoCredentialResolver resolver = new CollectionKeyInfoCredentialResolver(credentials); Decrypter decrypter = new Decrypter(null, resolver, encryptedKeyResolver); decrypter.setRootInNewDocument(true); return decrypter; } private LogoutRequestEncryptedIdUtils() { } }
3,223
38.317073
103
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutResponse.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.saml2.provider.service.authentication.logout; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.authentication.logout.Saml2LogoutResponseResolver; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * A class that represents a signed and serialized SAML 2.0 Logout Response * * @author Josh Cummings * @since 5.6 */ public final class Saml2LogoutResponse { private static final Function<Map<String, String>, String> DEFAULT_ENCODER = (params) -> { if (params.isEmpty()) { return null; } UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String> component : params.entrySet()) { builder.queryParam(component.getKey(), UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); } return builder.build(true).toString().substring(1); }; private final String location; private final Saml2MessageBinding binding; private final Map<String, String> parameters; private final Function<Map<String, String>, String> encoder; private Saml2LogoutResponse(String location, Saml2MessageBinding binding, Map<String, String> parameters, Function<Map<String, String>, String> encoder) { this.location = location; this.binding = binding; this.parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters)); this.encoder = encoder; } /** * Get the response location of the asserting party's <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * @return the SingleLogoutService response location */ public String getResponseLocation() { return this.location; } /** * Get the binding for the asserting party's <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * @return the SingleLogoutService binding */ public Saml2MessageBinding getBinding() { return this.binding; } /** * Get the signed and serialized &lt;saml2:LogoutResponse&gt; payload * @return the signed and serialized &lt;saml2:LogoutResponse&gt; payload */ public String getSamlResponse() { return this.parameters.get(Saml2ParameterNames.SAML_RESPONSE); } /** * The relay state associated with this Logout Request * @return the relay state */ public String getRelayState() { return this.parameters.get(Saml2ParameterNames.RELAY_STATE); } /** * Get the {@code name} parameter, a short-hand for <code> * getParameters().get(name) * </code> * * Useful when specifying additional query parameters for the Logout Response * @param name the parameter's name * @return the parameter's value */ public String getParameter(String name) { return this.parameters.get(name); } /** * Get all parameters * * Useful when specifying additional query parameters for the Logout Response * @return the Logout Response query parameters */ public Map<String, String> getParameters() { return this.parameters; } /** * Get an encoded query string of all parameters. Resulting query does not contain a * leading question mark. * @return an encoded string of all parameters * @since 5.8 */ public String getParametersQuery() { return this.encoder.apply(this.parameters); } /** * Create a {@link Builder} instance from this {@link RelyingPartyRegistration} * * Specifically, this will pull the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * response location and binding from the {@link RelyingPartyRegistration} * @param registration the {@link RelyingPartyRegistration} to use * @return the {@link Builder} for further configurations */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { return new Builder(registration); } public static final class Builder { private String location; private Saml2MessageBinding binding; private Map<String, String> parameters = new LinkedHashMap<>(); private Function<Map<String, String>, String> encoder = DEFAULT_ENCODER; private Builder(RelyingPartyRegistration registration) { this.location = registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation(); this.binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); } /** * Use this signed and serialized and Base64-encoded &lt;saml2:LogoutResponse&gt; * * Note that if using the Redirect binding, the value should be * {@link java.util.zip.DeflaterOutputStream deflated} and then Base64-encoded. * * It should not be URL-encoded as this will be done when the response is sent * @param samlResponse the &lt;saml2:LogoutResponse&gt; to use * @return the {@link Builder} for further configurations * @see Saml2LogoutResponseResolver */ public Builder samlResponse(String samlResponse) { this.parameters.put(Saml2ParameterNames.SAML_RESPONSE, samlResponse); return this; } /** * Use this SAML 2.0 Message Binding * * By default, the asserting party's configured binding is used * @param binding the SAML 2.0 Message Binding to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations */ public Builder binding(Saml2MessageBinding binding) { this.binding = binding; return this; } /** * Use this location for the SAML 2.0 logout endpoint * * By default, the asserting party's endpoint is used * @param location the SAML 2.0 location to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations */ public Builder location(String location) { this.location = location; return this; } /** * Use this value for the relay state when sending the Logout Request to the * asserting party * * It should not be URL-encoded as this will be done when the response is sent * @param relayState the relay state * @return the {@link Builder} for further configurations */ public Builder relayState(String relayState) { this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState); return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the response is * sent, though any signature specified should be Base64-encoded * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutResponse} * @return a constructed {@link Saml2LogoutResponse} */ public Saml2LogoutResponse build() { return new Saml2LogoutResponse(this.location, this.binding, this.parameters, this.encoder); } } }
8,652
32.933333
113
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutValidatorResult.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.saml2.provider.service.authentication.logout; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.function.Consumer; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.util.Assert; /** * A result emitted from a SAML 2.0 Logout validation attempt * * @author Josh Cummings * @since 5.6 */ public final class Saml2LogoutValidatorResult { static final Saml2LogoutValidatorResult NO_ERRORS = new Saml2LogoutValidatorResult(Collections.emptyList()); private final Collection<Saml2Error> errors; private Saml2LogoutValidatorResult(Collection<Saml2Error> errors) { Assert.notNull(errors, "errors cannot be null"); this.errors = new ArrayList<>(errors); } /** * Say whether this result indicates success * @return whether this result has errors */ public boolean hasErrors() { return !this.errors.isEmpty(); } /** * Return error details regarding the validation attempt * @return the collection of results in this result, if any; returns an empty list * otherwise */ public Collection<Saml2Error> getErrors() { return Collections.unmodifiableCollection(this.errors); } /** * Construct a successful {@link Saml2LogoutValidatorResult} * @return an {@link Saml2LogoutValidatorResult} with no errors */ public static Saml2LogoutValidatorResult success() { return NO_ERRORS; } /** * Construct a {@link Saml2LogoutValidatorResult.Builder}, starting with the given * {@code errors}. * * Note that a result with no errors is considered a success. * @param errors * @return */ public static Saml2LogoutValidatorResult.Builder withErrors(Saml2Error... errors) { return new Builder(errors); } public static final class Builder { private final Collection<Saml2Error> errors; private Builder(Saml2Error... errors) { this(Arrays.asList(errors)); } private Builder(Collection<Saml2Error> errors) { Assert.noNullElements(errors, "errors cannot have null elements"); this.errors = new ArrayList<>(errors); } public Builder errors(Consumer<Collection<Saml2Error>> errorsConsumer) { errorsConsumer.accept(this.errors); return this; } public Saml2LogoutValidatorResult build() { return new Saml2LogoutValidatorResult(this.errors); } } }
3,004
27.084112
109
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutRequestValidator.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.saml2.provider.service.authentication.logout; /** * Validates SAML 2.0 Logout Requests * * @author Josh Cummings * @since 5.6 */ public interface Saml2LogoutRequestValidator { /** * Authenticates the SAML 2.0 Logout Request received from the SAML 2.0 Asserting * Party. * * By default, verifies the signature, validates the issuer, destination, and user * identifier. * @param parameters the {@link Saml2LogoutRequestValidatorParameters} needed * @return the authentication result */ Saml2LogoutValidatorResult validate(Saml2LogoutRequestValidatorParameters parameters); }
1,259
31.307692
87
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutRequestValidatorParameters.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.saml2.provider.service.authentication.logout; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * A holder of the parameters needed to invoke {@link Saml2LogoutRequestValidator} * * @author Josh Cummings * @since 5.6 */ public class Saml2LogoutRequestValidatorParameters { private final Saml2LogoutRequest request; private final RelyingPartyRegistration registration; private final Authentication authentication; /** * Construct a {@link Saml2LogoutRequestValidatorParameters} * @param request the SAML 2.0 Logout Request received from the asserting party * @param registration the associated {@link RelyingPartyRegistration} * @param authentication the current user */ public Saml2LogoutRequestValidatorParameters(Saml2LogoutRequest request, RelyingPartyRegistration registration, Authentication authentication) { this.request = request; this.registration = registration; this.authentication = authentication; } /** * The SAML 2.0 Logout Request sent by the asserting party * @return the logout request */ public Saml2LogoutRequest getLogoutRequest() { return this.request; } /** * The {@link RelyingPartyRegistration} representing this relying party * @return the relying party */ public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } /** * The current {@link Authentication} * @return the authenticated user */ public Authentication getAuthentication() { return this.authentication; } }
2,270
29.689189
112
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlVerificationUtils.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.saml2.provider.service.authentication.logout; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import org.opensaml.core.criterion.EntityIdCriterion; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.criterion.ProtocolCriterion; import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.RequestAbstractType; import org.opensaml.saml.saml2.core.StatusResponseType; import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialResolver; import org.opensaml.security.credential.UsageType; import org.opensaml.security.credential.criteria.impl.EvaluableEntityIDCredentialCriterion; import org.opensaml.security.credential.criteria.impl.EvaluableUsageCredentialCriterion; import org.opensaml.security.credential.impl.CollectionCredentialResolver; import org.opensaml.security.criteria.UsageCriterion; import org.opensaml.security.x509.BasicX509Credential; import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap; import org.opensaml.xmlsec.signature.Signature; import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.web.util.UriComponentsBuilder; /** * Utility methods for verifying SAML component signatures with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlVerificationUtils { static VerifierPartial verifySignature(StatusResponseType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } static VerifierPartial verifySignature(RequestAbstractType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } private OpenSamlVerificationUtils() { } static class VerifierPartial { private final String id; private final CriteriaSet criteria; private final SignatureTrustEngine trustEngine; VerifierPartial(StatusResponseType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } VerifierPartial(RequestAbstractType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } Collection<Saml2Error> redirect(Saml2LogoutRequest request) { return redirect(new RedirectSignature(request)); } Collection<Saml2Error> redirect(Saml2LogoutResponse response) { return redirect(new RedirectSignature(response)); } Collection<Saml2Error> redirect(RedirectSignature signature) { if (signature.getAlgorithm() == null) { return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature algorithm for object [" + this.id + "]")); } if (!signature.hasSignature()) { return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature for object [" + this.id + "]")); } Collection<Saml2Error> errors = new ArrayList<>(); String algorithmUri = signature.getAlgorithm(); try { if (!this.trustEngine.validate(signature.getSignature(), signature.getContent(), algorithmUri, this.criteria, null)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return errors; } Collection<Saml2Error> post(Signature signature) { Collection<Saml2Error> errors = new ArrayList<>(); SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(signature); } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } try { if (!this.trustEngine.validate(signature, this.criteria)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return errors; } private CriteriaSet verificationCriteria(Issuer issuer) { CriteriaSet criteria = new CriteriaSet(); criteria.add(new EvaluableEntityIDCredentialCriterion(new EntityIdCriterion(issuer.getValue()))); criteria.add(new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS))); criteria.add(new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); return criteria; } private SignatureTrustEngine trustEngine(RelyingPartyRegistration registration) { Set<Credential> credentials = new HashSet<>(); Collection<Saml2X509Credential> keys = registration.getAssertingPartyDetails() .getVerificationX509Credentials(); for (Saml2X509Credential key : keys) { BasicX509Credential cred = new BasicX509Credential(key.getCertificate()); cred.setUsageType(UsageType.SIGNING); cred.setEntityId(registration.getAssertingPartyDetails().getEntityId()); credentials.add(cred); } CredentialResolver credentialsResolver = new CollectionCredentialResolver(credentials); return new ExplicitKeySignatureTrustEngine(credentialsResolver, DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver()); } private static class RedirectSignature { private final String algorithm; private final byte[] signature; private final byte[] content; RedirectSignature(Saml2LogoutRequest request) { this.algorithm = request.getParameter(Saml2ParameterNames.SIG_ALG); if (request.getParameter(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(request.getParameter(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance().query(request.getParametersQuery()) .build(true).getQueryParams().toSingleValueMap(); this.content = getContent(Saml2ParameterNames.SAML_REQUEST, request.getRelayState(), queryParams); } RedirectSignature(Saml2LogoutResponse response) { this.algorithm = response.getParameter(Saml2ParameterNames.SIG_ALG); if (response.getParameter(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(response.getParameter(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance() .query(response.getParametersQuery()).build(true).getQueryParams().toSingleValueMap(); this.content = getContent(Saml2ParameterNames.SAML_RESPONSE, response.getRelayState(), queryParams); } static byte[] getContent(String samlObject, String relayState, final Map<String, String> queryParams) { if (Objects.nonNull(relayState)) { return String .format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } else { return String.format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } } byte[] getContent() { return this.content; } String getAlgorithm() { return this.algorithm; } byte[] getSignature() { return this.signature; } boolean hasSignature() { return this.signature != null; } } } }
9,482
36.932
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutResponseValidator.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.saml2.provider.service.authentication.logout; /** * Validates SAML 2.0 Logout Responses * * @author Josh Cummings * @since 5.6 */ public interface Saml2LogoutResponseValidator { /** * Authenticates the SAML 2.0 Logout Response received from the SAML 2.0 Asserting * Party. * * By default, verifies the signature, validates the issuer, destination, and status. * It also ensures that it aligns with the given logout request. * @param parameters the {@link Saml2LogoutResponseValidatorParameters} needed * @return the authentication result */ Saml2LogoutValidatorResult validate(Saml2LogoutResponseValidatorParameters parameters); }
1,317
32.794872
88
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutRequest.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.saml2.provider.service.authentication.logout; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.authentication.logout.Saml2LogoutRequestResolver; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * A class that represents a signed and serialized SAML 2.0 Logout Request * * @author Josh Cummings * @since 5.6 */ public final class Saml2LogoutRequest implements Serializable { private static final Function<Map<String, String>, String> DEFAULT_ENCODER = (params) -> { if (params.isEmpty()) { return null; } UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String> component : params.entrySet()) { builder.queryParam(component.getKey(), UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); } return builder.build(true).toString().substring(1); }; private final String location; private final Saml2MessageBinding binding; private final Map<String, String> parameters; private final String id; private final String relyingPartyRegistrationId; private transient Function<Map<String, String>, String> encoder; private Saml2LogoutRequest(String location, Saml2MessageBinding binding, Map<String, String> parameters, String id, String relyingPartyRegistrationId) { this(location, binding, parameters, id, relyingPartyRegistrationId, DEFAULT_ENCODER); } private Saml2LogoutRequest(String location, Saml2MessageBinding binding, Map<String, String> parameters, String id, String relyingPartyRegistrationId, Function<Map<String, String>, String> encoder) { this.location = location; this.binding = binding; this.parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters)); this.id = id; this.relyingPartyRegistrationId = relyingPartyRegistrationId; this.encoder = encoder; } /** * The unique identifier for this Logout Request * @return the Logout Request identifier */ public String getId() { return this.id; } /** * Get the location of the asserting party's <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * @return the SingleLogoutService location */ public String getLocation() { return this.location; } /** * Get the binding for the asserting party's <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * @return the SingleLogoutService binding */ public Saml2MessageBinding getBinding() { return this.binding; } /** * Get the signed and serialized &lt;saml2:LogoutRequest&gt; payload * @return the signed and serialized &lt;saml2:LogoutRequest&gt; payload */ public String getSamlRequest() { return this.parameters.get(Saml2ParameterNames.SAML_REQUEST); } /** * The relay state associated with this Logout Request * @return the relay state */ public String getRelayState() { return this.parameters.get(Saml2ParameterNames.RELAY_STATE); } /** * Get the {@code name} parameters, a short-hand for <code> * getParameters().get(name) * </code> * * Useful when specifying additional query parameters for the Logout Request * @param name the parameter's name * @return the parameter's value */ public String getParameter(String name) { return this.parameters.get(name); } /** * Get all parameters * * Useful when specifying additional query parameters for the Logout Request * @return the Logout Request query parameters */ public Map<String, String> getParameters() { return this.parameters; } /** * Get an encoded query string of all parameters. Resulting query does not contain a * leading question mark. * @return an encoded string of all parameters * @since 5.8 */ public String getParametersQuery() { return this.encoder.apply(this.parameters); } /** * The identifier for the {@link RelyingPartyRegistration} associated with this Logout * Request * @return the {@link RelyingPartyRegistration} id */ public String getRelyingPartyRegistrationId() { return this.relyingPartyRegistrationId; } /** * Create a {@link Builder} instance from this {@link RelyingPartyRegistration} * * Specifically, this will pull the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService</a> * location and binding from the {@link RelyingPartyRegistration} * @param registration the {@link RelyingPartyRegistration} to use * @return the {@link Builder} for further configurations */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { return new Builder(registration); } public static final class Builder { private final RelyingPartyRegistration registration; private String location; private Saml2MessageBinding binding; private Map<String, String> parameters = new LinkedHashMap<>(); private Function<Map<String, String>, String> encoder = DEFAULT_ENCODER; private String id; private Builder(RelyingPartyRegistration registration) { this.registration = registration; this.location = registration.getAssertingPartyDetails().getSingleLogoutServiceLocation(); this.binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); } /** * Use this signed and serialized and Base64-encoded &lt;saml2:LogoutRequest&gt; * * Note that if using the Redirect binding, the value should be * {@link java.util.zip.DeflaterOutputStream deflated} and then Base64-encoded. * * It should not be URL-encoded as this will be done when the request is sent * @param samlRequest the &lt;saml2:LogoutRequest&gt; to use * @return the {@link Builder} for further configurations * @see Saml2LogoutRequestResolver */ public Builder samlRequest(String samlRequest) { this.parameters.put(Saml2ParameterNames.SAML_REQUEST, samlRequest); return this; } /** * Use this SAML 2.0 Message Binding * * By default, the asserting party's configured binding is used * @param binding the SAML 2.0 Message Binding to use * @return the {@link Builder} for further configurations */ public Builder binding(Saml2MessageBinding binding) { this.binding = binding; return this; } /** * Use this location for the SAML 2.0 logout endpoint * * By default, the asserting party's endpoint is used * @param location the SAML 2.0 location to use * @return the {@link Builder} for further configurations */ public Builder location(String location) { this.location = location; return this; } /** * Use this value for the relay state when sending the Logout Request to the * asserting party * * It should not be URL-encoded as this will be done when the request is sent * @param relayState the relay state * @return the {@link Builder} for further configurations */ public Builder relayState(String relayState) { this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState); return this; } /** * This is the unique id used in the {@link #samlRequest} * @param id the Logout Request id * @return the {@link Builder} for further configurations */ public Builder id(String id) { this.id = id; return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the request is * sent * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutRequest} * @return a constructed {@link Saml2LogoutRequest} */ public Saml2LogoutRequest build() { return new Saml2LogoutRequest(this.location, this.binding, this.parameters, this.id, this.registration.getRegistrationId(), this.encoder); } } }
9,794
31.65
116
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/Saml2MetadataResolver.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.saml2.provider.service.metadata; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * Resolves the SAML 2.0 Relying Party Metadata for a given * {@link RelyingPartyRegistration} * * @author Jakub Kubrynski * @author Josh Cummings * @since 5.4 */ public interface Saml2MetadataResolver { /** * Resolve the given relying party's metadata * @param relyingPartyRegistration the relying party * @return the relying party's metadata */ String resolve(RelyingPartyRegistration relyingPartyRegistration); default String resolve(Iterable<RelyingPartyRegistration> relyingPartyRegistrations) { return resolve(relyingPartyRegistrations.iterator().next()); } }
1,386
31.255814
97
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/Saml2MetadataResponseResolver.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.saml2.provider.service.metadata; import jakarta.servlet.http.HttpServletRequest; /** * Resolves Relying Party SAML 2.0 Metadata given details from the * {@link HttpServletRequest}. * * @author Josh Cummings * @since 6.1 */ public interface Saml2MetadataResponseResolver { /** * Construct and serialize a relying party's SAML 2.0 metadata based on the given * {@link HttpServletRequest} * @param request the HTTP request * @return a {@link Saml2MetadataResponse} instance */ Saml2MetadataResponse resolve(HttpServletRequest request); }
1,217
30.230769
82
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/RequestMatcherMetadataResponseResolver.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.saml2.provider.service.metadata; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * An implementation of {@link Saml2MetadataResponseResolver} that identifies which * {@link RelyingPartyRegistration}s to use with a {@link RequestMatcher} * * @author Josh Cummings * @since 6.1 */ public final class RequestMatcherMetadataResponseResolver implements Saml2MetadataResponseResolver { private static final String DEFAULT_METADATA_FILENAME = "saml-{registrationId}-metadata.xml"; private RequestMatcher matcher = new OrRequestMatcher( new AntPathRequestMatcher("/saml2/service-provider-metadata/{registrationId}"), new AntPathRequestMatcher("/saml2/metadata/{registrationId}"), new AntPathRequestMatcher("/saml2/metadata")); private String filename = DEFAULT_METADATA_FILENAME; private final RelyingPartyRegistrationRepository registrations; private final Saml2MetadataResolver metadata; /** * Construct a {@link RequestMatcherMetadataResponseResolver} * @param registrations the source for relying party metadata * @param metadata the strategy for converting {@link RelyingPartyRegistration}s into * metadata */ public RequestMatcherMetadataResponseResolver(RelyingPartyRegistrationRepository registrations, Saml2MetadataResolver metadata) { Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); Assert.notNull(metadata, "saml2MetadataResolver cannot be null"); this.registrations = registrations; this.metadata = metadata; } /** * Construct and serialize a relying party's SAML 2.0 metadata based on the given * {@link HttpServletRequest}. Uses the configured {@link RequestMatcher} to identify * the metadata request, including looking for any indicated {@code registrationId}. * * <p> * If a {@code registrationId} is found in the request, it will attempt to use that, * erroring if no {@link RelyingPartyRegistration} is found. * * <p> * If no {@code registrationId} is found in the request, it will attempt to show all * {@link RelyingPartyRegistration}s in an {@code <md:EntitiesDescriptor>}. To * exercise this functionality, the provided * {@link RelyingPartyRegistrationRepository} needs to implement {@link Iterable}. * @param request the HTTP request * @return a {@link Saml2MetadataResponse} instance * @throws Saml2Exception if the {@link RequestMatcher} specifies a non-existent * {@code registrationId} */ @Override public Saml2MetadataResponse resolve(HttpServletRequest request) { RequestMatcher.MatchResult result = this.matcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = result.getVariables().get("registrationId"); Saml2MetadataResponse response = responseByRegistrationId(request, registrationId); if (response != null) { return response; } if (this.registrations instanceof Iterable<?>) { Iterable<RelyingPartyRegistration> registrations = (Iterable<RelyingPartyRegistration>) this.registrations; return responseByIterable(request, registrations); } return null; } private Saml2MetadataResponse responseByRegistrationId(HttpServletRequest request, String registrationId) { if (registrationId == null) { return null; } RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId); if (registration == null) { throw new Saml2Exception("registration not found"); } return responseByIterable(request, Collections.singleton(registration)); } private Saml2MetadataResponse responseByIterable(HttpServletRequest request, Iterable<RelyingPartyRegistration> registrations) { Map<String, RelyingPartyRegistration> results = new LinkedHashMap<>(); for (RelyingPartyRegistration registration : registrations) { results.put(registration.getEntityId(), registration); } Collection<RelyingPartyRegistration> resolved = new ArrayList<>(); for (RelyingPartyRegistration registration : results.values()) { UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); String ssoLocation = uriResolver.resolve(registration.getAssertionConsumerServiceLocation()); String sloLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); String sloResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); resolved.add(registration.mutate().entityId(entityId).assertionConsumerServiceLocation(ssoLocation) .singleLogoutServiceLocation(sloLocation).singleLogoutServiceResponseLocation(sloResponseLocation) .build()); } String metadata = this.metadata.resolve(resolved); String value = (resolved.size() == 1) ? resolved.iterator().next().getRegistrationId() : UUID.randomUUID().toString(); String fileName = this.filename.replace("{registrationId}", value); try { String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); return new Saml2MetadataResponse(metadata, encodedFileName); } catch (UnsupportedEncodingException ex) { throw new Saml2Exception(ex); } } /** * Use this {@link RequestMatcher} to identity which requests to generate metadata * for. By default, matches {@code /saml2/metadata}, * {@code /saml2/metadata/{registrationId}}, {@code /saml2/service-provider-metadata}, * and {@code /saml2/service-provider-metadata/{registrationId}} * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be empty"); this.matcher = requestMatcher; } /** * Sets the metadata filename template. If it contains the {@code {registrationId}} * placeholder, it will be resolved as a random UUID if there are multiple * {@link RelyingPartyRegistration}s. Otherwise, it will be replaced by the * {@link RelyingPartyRegistration}'s id. * * <p> * The default value is {@code saml-{registrationId}-metadata.xml} * @param metadataFilename metadata filename, must contain a {registrationId} */ public void setMetadataFilename(String metadataFilename) { Assert.hasText(metadataFilename, "metadataFilename cannot be empty"); this.filename = metadataFilename; } }
8,024
42.852459
120
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/Saml2MetadataResponse.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.saml2.provider.service.metadata; public class Saml2MetadataResponse { private final String metadata; private final String fileName; public Saml2MetadataResponse(String metadata, String fileName) { this.metadata = metadata; this.fileName = fileName; } public String getMetadata() { return this.metadata; } public String getFileName() { return this.fileName; } }
1,044
25.794872
75
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.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.saml2.provider.service.metadata; import java.security.cert.CertificateEncodingException; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import javax.xml.namespace.QName; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObjectBuilder; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.saml.saml2.metadata.KeyDescriptor; import org.opensaml.saml.saml2.metadata.NameIDFormat; import org.opensaml.saml.saml2.metadata.SPSSODescriptor; import org.opensaml.saml.saml2.metadata.SingleLogoutService; import org.opensaml.saml.saml2.metadata.impl.EntitiesDescriptorMarshaller; import org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.signature.KeyInfo; import org.opensaml.xmlsec.signature.X509Certificate; import org.opensaml.xmlsec.signature.X509Data; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.util.Assert; /** * Resolves the SAML 2.0 Relying Party Metadata for a given * {@link RelyingPartyRegistration} using the OpenSAML API. * * @author Jakub Kubrynski * @author Josh Cummings * @since 5.4 */ public final class OpenSamlMetadataResolver implements Saml2MetadataResolver { static { OpenSamlInitializationService.initialize(); } private final EntityDescriptorMarshaller entityDescriptorMarshaller; private final EntitiesDescriptorMarshaller entitiesDescriptorMarshaller; private Consumer<EntityDescriptorParameters> entityDescriptorCustomizer = (parameters) -> { }; public OpenSamlMetadataResolver() { this.entityDescriptorMarshaller = (EntityDescriptorMarshaller) XMLObjectProviderRegistrySupport .getMarshallerFactory().getMarshaller(EntityDescriptor.DEFAULT_ELEMENT_NAME); Assert.notNull(this.entityDescriptorMarshaller, "entityDescriptorMarshaller cannot be null"); this.entitiesDescriptorMarshaller = (EntitiesDescriptorMarshaller) XMLObjectProviderRegistrySupport .getMarshallerFactory().getMarshaller(EntitiesDescriptor.DEFAULT_ELEMENT_NAME); Assert.notNull(this.entitiesDescriptorMarshaller, "entitiesDescriptorMarshaller cannot be null"); } @Override public String resolve(RelyingPartyRegistration relyingPartyRegistration) { EntityDescriptor entityDescriptor = entityDescriptor(relyingPartyRegistration); return serialize(entityDescriptor); } public String resolve(Iterable<RelyingPartyRegistration> relyingPartyRegistrations) { Collection<EntityDescriptor> entityDescriptors = new ArrayList<>(); for (RelyingPartyRegistration registration : relyingPartyRegistrations) { EntityDescriptor entityDescriptor = entityDescriptor(registration); entityDescriptors.add(entityDescriptor); } if (entityDescriptors.size() == 1) { return serialize(entityDescriptors.iterator().next()); } EntitiesDescriptor entities = build(EntitiesDescriptor.DEFAULT_ELEMENT_NAME); entities.getEntityDescriptors().addAll(entityDescriptors); return serialize(entities); } private EntityDescriptor entityDescriptor(RelyingPartyRegistration registration) { EntityDescriptor entityDescriptor = build(EntityDescriptor.DEFAULT_ELEMENT_NAME); entityDescriptor.setEntityID(registration.getEntityId()); SPSSODescriptor spSsoDescriptor = buildSpSsoDescriptor(registration); entityDescriptor.getRoleDescriptors(SPSSODescriptor.DEFAULT_ELEMENT_NAME).add(spSsoDescriptor); this.entityDescriptorCustomizer.accept(new EntityDescriptorParameters(entityDescriptor, registration)); return entityDescriptor; } /** * Set a {@link Consumer} for modifying the OpenSAML {@link EntityDescriptor} * @param entityDescriptorCustomizer a consumer that accepts an * {@link EntityDescriptorParameters} * @since 5.7 */ public void setEntityDescriptorCustomizer(Consumer<EntityDescriptorParameters> entityDescriptorCustomizer) { Assert.notNull(entityDescriptorCustomizer, "entityDescriptorCustomizer cannot be null"); this.entityDescriptorCustomizer = entityDescriptorCustomizer; } private SPSSODescriptor buildSpSsoDescriptor(RelyingPartyRegistration registration) { SPSSODescriptor spSsoDescriptor = build(SPSSODescriptor.DEFAULT_ELEMENT_NAME); spSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); spSsoDescriptor.getKeyDescriptors() .addAll(buildKeys(registration.getSigningX509Credentials(), UsageType.SIGNING)); spSsoDescriptor.getKeyDescriptors() .addAll(buildKeys(registration.getDecryptionX509Credentials(), UsageType.ENCRYPTION)); spSsoDescriptor.getAssertionConsumerServices().add(buildAssertionConsumerService(registration)); if (registration.getSingleLogoutServiceLocation() != null) { for (Saml2MessageBinding binding : registration.getSingleLogoutServiceBindings()) { spSsoDescriptor.getSingleLogoutServices().add(buildSingleLogoutService(registration, binding)); } } if (registration.getNameIdFormat() != null) { spSsoDescriptor.getNameIDFormats().add(buildNameIDFormat(registration)); } return spSsoDescriptor; } private List<KeyDescriptor> buildKeys(Collection<Saml2X509Credential> credentials, UsageType usageType) { List<KeyDescriptor> list = new ArrayList<>(); for (Saml2X509Credential credential : credentials) { KeyDescriptor keyDescriptor = buildKeyDescriptor(usageType, credential.getCertificate()); list.add(keyDescriptor); } return list; } private KeyDescriptor buildKeyDescriptor(UsageType usageType, java.security.cert.X509Certificate certificate) { KeyDescriptor keyDescriptor = build(KeyDescriptor.DEFAULT_ELEMENT_NAME); KeyInfo keyInfo = build(KeyInfo.DEFAULT_ELEMENT_NAME); X509Certificate x509Certificate = build(X509Certificate.DEFAULT_ELEMENT_NAME); X509Data x509Data = build(X509Data.DEFAULT_ELEMENT_NAME); try { x509Certificate.setValue(new String(Base64.getEncoder().encode(certificate.getEncoded()))); } catch (CertificateEncodingException ex) { throw new Saml2Exception("Cannot encode certificate " + certificate.toString()); } x509Data.getX509Certificates().add(x509Certificate); keyInfo.getX509Datas().add(x509Data); keyDescriptor.setUse(usageType); keyDescriptor.setKeyInfo(keyInfo); return keyDescriptor; } private AssertionConsumerService buildAssertionConsumerService(RelyingPartyRegistration registration) { AssertionConsumerService assertionConsumerService = build(AssertionConsumerService.DEFAULT_ELEMENT_NAME); assertionConsumerService.setLocation(registration.getAssertionConsumerServiceLocation()); assertionConsumerService.setBinding(registration.getAssertionConsumerServiceBinding().getUrn()); assertionConsumerService.setIndex(1); return assertionConsumerService; } private SingleLogoutService buildSingleLogoutService(RelyingPartyRegistration registration, Saml2MessageBinding binding) { SingleLogoutService singleLogoutService = build(SingleLogoutService.DEFAULT_ELEMENT_NAME); singleLogoutService.setLocation(registration.getSingleLogoutServiceLocation()); singleLogoutService.setResponseLocation(registration.getSingleLogoutServiceResponseLocation()); singleLogoutService.setBinding(binding.getUrn()); return singleLogoutService; } private NameIDFormat buildNameIDFormat(RelyingPartyRegistration registration) { NameIDFormat nameIdFormat = build(NameIDFormat.DEFAULT_ELEMENT_NAME); nameIdFormat.setURI(registration.getNameIdFormat()); return nameIdFormat; } @SuppressWarnings("unchecked") private <T> T build(QName elementName) { XMLObjectBuilder<?> builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(elementName); if (builder == null) { throw new Saml2Exception("Unable to resolve Builder for " + elementName); } return (T) builder.buildObject(elementName); } private String serialize(EntityDescriptor entityDescriptor) { try { Element element = this.entityDescriptorMarshaller.marshall(entityDescriptor); return SerializeSupport.prettyPrintXML(element); } catch (Exception ex) { throw new Saml2Exception(ex); } } private String serialize(EntitiesDescriptor entities) { try { Element element = this.entitiesDescriptorMarshaller.marshall(entities); return SerializeSupport.prettyPrintXML(element); } catch (Exception ex) { throw new Saml2Exception(ex); } } /** * A tuple containing an OpenSAML {@link EntityDescriptor} and its associated * {@link RelyingPartyRegistration} * * @since 5.7 */ public static final class EntityDescriptorParameters { private final EntityDescriptor entityDescriptor; private final RelyingPartyRegistration registration; public EntityDescriptorParameters(EntityDescriptor entityDescriptor, RelyingPartyRegistration registration) { this.entityDescriptor = entityDescriptor; this.registration = registration; } public EntityDescriptor getEntityDescriptor() { return this.entityDescriptor; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } } }
10,379
40.52
112
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/ClientAuthenticationMethodTests.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.oauth2.core; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClientAuthenticationMethod}. * * @author Joe Grandja */ public class ClientAuthenticationMethodTests { @Test public void constructorWhenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new ClientAuthenticationMethod(null)); } @Test public void getValueWhenAuthenticationMethodClientSecretBasicThenReturnClientSecretBasic() { assertThat(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()).isEqualTo("client_secret_basic"); } @Test public void getValueWhenAuthenticationMethodClientSecretPostThenReturnClientSecretPost() { assertThat(ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue()).isEqualTo("client_secret_post"); } @Test public void getValueWhenAuthenticationMethodClientSecretJwtThenReturnClientSecretJwt() { assertThat(ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue()).isEqualTo("client_secret_jwt"); } @Test public void getValueWhenAuthenticationMethodPrivateKeyJwtThenReturnPrivateKeyJwt() { assertThat(ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue()).isEqualTo("private_key_jwt"); } @Test public void getValueWhenAuthenticationMethodNoneThenReturnNone() { assertThat(ClientAuthenticationMethod.NONE.getValue()).isEqualTo("none"); } }
2,138
33.5
105
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2TokenIntrospectionClaimAccessorTests.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.oauth2.core; import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNullPointerException; /** * Tests for {@link OAuth2TokenIntrospectionClaimAccessor}. * * @author David Kovac */ public class OAuth2TokenIntrospectionClaimAccessorTests { private final Map<String, Object> claims = new HashMap<>(); private final OAuth2TokenIntrospectionClaimAccessor claimAccessor = (() -> this.claims); @BeforeEach public void setup() { this.claims.clear(); } @Test public void isActiveWhenActiveClaimNotExistingThenReturnFalse() { assertThat(this.claimAccessor.isActive()).isFalse(); } @Test public void isActiveWhenActiveClaimValueIsNullThenThrowsNullPointerException() { this.claims.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, null); assertThatNullPointerException().isThrownBy(this.claimAccessor::isActive); } @Test public void isActiveWhenActiveClaimValueIsTrueThenReturnTrue() { this.claims.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, "true"); assertThat(this.claimAccessor.isActive()).isTrue(); } @Test public void getUsernameWhenUsernameClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getUsername()).isNull(); } @Test public void getUsernameWhenUsernameClaimExistingThenReturnUsername() { String expectedUsernameValue = "username"; this.claims.put(OAuth2TokenIntrospectionClaimNames.USERNAME, expectedUsernameValue); assertThat(this.claimAccessor.getUsername()).isEqualTo(expectedUsernameValue); } @Test public void getClientIdWhenClientIdClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getUsername()).isNull(); } @Test public void getClientIdWhenClientIdClaimExistingThenReturnClientId() { String expectedClientIdValue = "clientId"; this.claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, expectedClientIdValue); assertThat(this.claimAccessor.getClientId()).isEqualTo(expectedClientIdValue); } @Test public void getScopesWhenScopeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getScopes()).isNull(); } @Test public void getScopesWhenScopeClaimExistingThenReturnScope() { List<String> expectedScopeValue = Arrays.asList("scope1", "scope2"); this.claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, expectedScopeValue); assertThat(this.claimAccessor.getScopes()).hasSameElementsAs(expectedScopeValue); } @Test public void getTokenTypeWhenTokenTypeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getTokenType()).isNull(); } @Test public void getTokenTypeWhenTokenTypeClaimExistingThenReturnTokenType() { String expectedTokenTypeValue = "tokenType"; this.claims.put(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE, expectedTokenTypeValue); assertThat(this.claimAccessor.getTokenType()).isEqualTo(expectedTokenTypeValue); } @Test public void getExpiresAtWhenExpiresAtClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getExpiresAt()).isNull(); } @Test public void getExpiresAtWhenExpiresAtClaimExistingThenReturnExpiresAt() { Instant expectedExpiresAtValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.EXP, expectedExpiresAtValue); assertThat(this.claimAccessor.getExpiresAt()).isEqualTo(expectedExpiresAtValue); } @Test public void getIssuedAtWhenIssuedAtClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getExpiresAt()).isNull(); } @Test public void getIssuedAtWhenIssuedAtClaimExistingThenReturnIssuedAt() { Instant expectedIssuedAtValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.IAT, expectedIssuedAtValue); assertThat(this.claimAccessor.getIssuedAt()).isEqualTo(expectedIssuedAtValue); } @Test public void getNotBeforeWhenNotBeforeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getNotBefore()).isNull(); } @Test public void getNotBeforeWhenNotBeforeClaimExistingThenReturnNotBefore() { Instant expectedNotBeforeValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.NBF, expectedNotBeforeValue); assertThat(this.claimAccessor.getNotBefore()).isEqualTo(expectedNotBeforeValue); } @Test public void getSubjectWhenSubjectClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getSubject()).isNull(); } @Test public void getSubjectWhenSubjectClaimExistingThenReturnSubject() { String expectedSubjectValue = "subject"; this.claims.put(OAuth2TokenIntrospectionClaimNames.SUB, expectedSubjectValue); assertThat(this.claimAccessor.getSubject()).isEqualTo(expectedSubjectValue); } @Test public void getAudienceWhenAudienceClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getAudience()).isNull(); } @Test public void getAudienceWhenAudienceClaimExistingThenReturnAudience() { List<String> expectedAudienceValue = Arrays.asList("audience1", "audience2"); this.claims.put(OAuth2TokenIntrospectionClaimNames.AUD, expectedAudienceValue); assertThat(this.claimAccessor.getAudience()).hasSameElementsAs(expectedAudienceValue); } @Test public void getIssuerWhenIssuerClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getIssuer()).isNull(); } @Test public void getIssuerWhenIssuerClaimExistingThenReturnIssuer() throws MalformedURLException { URL expectedIssuerValue = new URL("https://issuer.com"); this.claims.put(OAuth2TokenIntrospectionClaimNames.ISS, expectedIssuerValue); assertThat(this.claimAccessor.getIssuer()).isEqualTo(expectedIssuerValue); } @Test public void getIdWhenJtiClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getId()).isNull(); } @Test public void getIdWhenJtiClaimExistingThenReturnId() { String expectedIdValue = "id"; this.claims.put(OAuth2TokenIntrospectionClaimNames.JTI, expectedIdValue); assertThat(this.claimAccessor.getId()).isEqualTo(expectedIdValue); } }
6,812
33.236181
94
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.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.oauth2.core; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultOAuth2AuthenticatedPrincipal} * * @author Josh Cummings */ public class DefaultOAuth2AuthenticatedPrincipalTests { String name = "test-subject"; Map<String, Object> attributes = Collections.singletonMap("sub", this.name); Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read"); @Test public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(null, this.authorities)); assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(Collections.emptyMap(), this.authorities)); } @Test public void constructorWhenAuthoritiesIsNullOrEmptyThenNoAuthorities() { Collection<? extends GrantedAuthority> authorities = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, null).getAuthorities(); assertThat(authorities).isEmpty(); authorities = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, Collections.emptyList()) .getAuthorities(); assertThat(authorities).isEmpty(); } @Test public void constructorWhenNameIsNullThenFallsbackToSubAttribute() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(null, this.attributes, this.authorities); assertThat(principal.getName()).isEqualTo(this.attributes.get("sub")); } @Test public void getNameWhenInConstructorThenReturns() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal("other-subject", this.attributes, this.authorities); assertThat(principal.getName()).isEqualTo("other-subject"); } @Test public void getAttributeWhenGivenKeyThenReturnsValue() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, this.authorities); assertThat((String) principal.getAttribute("sub")).isEqualTo("test-subject"); } }
3,026
35.035714
111
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/ClaimAccessorTests.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.oauth2.core; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.assertj.core.api.Assertions.assertThatObject; /** * Tests for {@link ClaimAccessor}. * * @author Joe Grandja */ public class ClaimAccessorTests { private Map<String, Object> claims = new HashMap<>(); private ClaimAccessor claimAccessor = (() -> this.claims); @BeforeEach public void setup() { this.claims.clear(); } // gh-5192 @Test public void getClaimAsInstantWhenDateTypeThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "date"; this.claims.put(claimName, Date.from(expectedClaimValue)); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween(expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); } // gh-5191 @Test public void getClaimAsInstantWhenLongTypeSecondsThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "longSeconds"; this.claims.put(claimName, expectedClaimValue.getEpochSecond()); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween(expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); } @Test public void getClaimAsInstantWhenInstantTypeThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "instant"; this.claims.put(claimName, expectedClaimValue); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween(expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); } // gh-5250 @Test public void getClaimAsInstantWhenIntegerTypeSecondsThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "integerSeconds"; this.claims.put(claimName, Long.valueOf(expectedClaimValue.getEpochSecond()).intValue()); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween(expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); } // gh-5250 @Test public void getClaimAsInstantWhenDoubleTypeSecondsThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "doubleSeconds"; this.claims.put(claimName, Long.valueOf(expectedClaimValue.getEpochSecond()).doubleValue()); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween(expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); } // gh-5608 @Test public void getClaimAsStringWhenValueIsNullThenReturnNull() { String claimName = "claim-with-null-value"; this.claims.put(claimName, null); assertThat(this.claimAccessor.getClaimAsString(claimName)).isNull(); } @Test public void getClaimAsBooleanWhenBooleanTypeThenReturnBoolean() { Boolean expectedClaimValue = Boolean.TRUE; String claimName = "boolean"; this.claims.put(claimName, expectedClaimValue); assertThat(this.claimAccessor.getClaimAsBoolean(claimName)).isEqualTo(expectedClaimValue); } @Test public void getClaimAsBooleanWhenStringTypeThenReturnBoolean() { Boolean expectedClaimValue = Boolean.TRUE; String claimName = "boolean"; this.claims.put(claimName, expectedClaimValue.toString()); assertThat(this.claimAccessor.getClaimAsBoolean(claimName)).isEqualTo(expectedClaimValue); } // gh-10148 @Test public void getClaimAsBooleanWhenNonBooleanTypeThenThrowIllegalArgumentException() { String claimName = "boolean"; Map<Object, Object> claimValue = new HashMap<>(); this.claims.put(claimName, claimValue); assertThatIllegalArgumentException().isThrownBy(() -> this.claimAccessor.getClaimAsBoolean(claimName)) .withMessage("Unable to convert claim '" + claimName + "' of type '" + claimValue.getClass() + "' to Boolean."); } @Test public void getClaimAsMapWhenNotExistingThenReturnNull() { assertThat(this.claimAccessor.getClaimAsMap("map")).isNull(); } @Test public void getClaimAsMapWhenMapTypeThenReturnMap() { Map<Object, Object> expectedClaimValue = Collections.emptyMap(); String claimName = "map"; this.claims.put(claimName, expectedClaimValue); assertThat(this.claimAccessor.getClaimAsMap(claimName)).isEqualTo(expectedClaimValue); } @Test public void getClaimAsMapWhenValueIsNullThenThrowNullPointerException() { String claimName = "map"; this.claims.put(claimName, null); assertThatNullPointerException().isThrownBy(() -> this.claimAccessor.getClaimAsMap(claimName)); } @Test public void getClaimAsMapWhenNonMapTypeThenThrowIllegalArgumentException() { String claimName = "map"; this.claims.put(claimName, "map"); assertThatIllegalArgumentException().isThrownBy(() -> this.claimAccessor.getClaimAsMap(claimName)); } @Test public void getClaimAsStringListWhenNotExistingThenReturnNull() { assertThat(this.claimAccessor.getClaimAsStringList("list")).isNull(); } @Test public void getClaimAsStringListWhenStringListTypeThenReturnList() { List<String> expectedClaimValue = Collections.emptyList(); String claimName = "list"; this.claims.put(claimName, expectedClaimValue); assertThat(this.claimAccessor.getClaimAsStringList(claimName)).isEqualTo(expectedClaimValue); } @Test public void getClaimAsStringListWhenNonListTypeThenReturnList() { List<String> expectedClaimValue = Collections.singletonList("list"); String claimName = "list"; this.claims.put(claimName, expectedClaimValue.get(0)); assertThat(this.claimAccessor.getClaimAsStringList(claimName)).isEqualTo(expectedClaimValue); } @Test public void getClaimAsStringListWhenValueIsNullThenNullPointerException() { String claimName = "list"; this.claims.put(claimName, null); assertThatNullPointerException().isThrownBy(() -> this.claimAccessor.getClaimAsStringList(claimName)); } @Test public void getClaimWhenNotExistingThenReturnNull() { String claimName = "list"; List<String> actualClaimValue = this.claimAccessor.getClaim(claimName); assertThat(actualClaimValue).isNull(); } @Test public void getClaimWhenValueIsConvertedThenReturnList() { List<String> expectedClaimValue = Arrays.asList("item1", "item2"); String claimName = "list"; this.claims.put(claimName, expectedClaimValue); List<String> actualClaimValue = this.claimAccessor.getClaim(claimName); assertThat(actualClaimValue).containsOnlyElementsOf(expectedClaimValue); } @Test public void getClaimWhenValueIsConvertedThenReturnBoolean() { boolean expectedClaimValue = true; String claimName = "boolean"; this.claims.put(claimName, expectedClaimValue); boolean actualClaimValue = this.claimAccessor.getClaim(claimName); assertThat(actualClaimValue).isEqualTo(expectedClaimValue); } @Test public void getClaimWhenValueIsNotConvertedThenThrowClassCastException() { String expectedClaimValue = "true"; String claimName = "boolean"; this.claims.put(claimName, expectedClaimValue); assertThatObject(this.claimAccessor.getClaim(claimName)).isNotInstanceOf(Boolean.class); } }
7,962
34.549107
107
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.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.oauth2.core; import java.util.Arrays; import java.util.Collection; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests for verifying {@link DelegatingOAuth2TokenValidator} * * @author Josh Cummings */ public class DelegatingOAuth2TokenValidatorTests { private static final OAuth2Error DETAIL = new OAuth2Error("error", "description", "uri"); @Test public void validateWhenNoValidatorsConfiguredThenReturnsSuccessfulResult() { DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(); OAuth2Token token = mock(OAuth2Token.class); assertThat(tokenValidator.validate(token).hasErrors()).isFalse(); } @Test public void validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator() { OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class); OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class); given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL)); DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(success, failure)); OAuth2Token token = mock(OAuth2Token.class); OAuth2TokenValidatorResult result = tokenValidator.validate(token); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors()).containsExactly(DETAIL); } @Test public void validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails() { OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class); OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class); OAuth2Error otherDetail = new OAuth2Error("another-error"); given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL)); given(secondFailure.validate(any(OAuth2Token.class))) .willReturn(OAuth2TokenValidatorResult.failure(otherDetail)); DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure); OAuth2Token token = mock(OAuth2Token.class); OAuth2TokenValidatorResult result = tokenValidator.validate(token); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail); } @Test public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() { OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class); OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class); given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(firstSuccess, secondSuccess)); OAuth2Token token = mock(OAuth2Token.class); OAuth2TokenValidatorResult result = tokenValidator.validate(token); assertThat(result.hasErrors()).isFalse(); assertThat(result.getErrors()).isEmpty(); } @Test public void constructorWhenInvokedWithNullValidatorListThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new DelegatingOAuth2TokenValidator<>((Collection<OAuth2TokenValidator<OAuth2Token>>) null)); } @Test public void constructorsWhenInvokedWithSameInputsThenResultInSameOutputs() { OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class); OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class); given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(firstSuccess, secondSuccess)); DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess); OAuth2Token token = mock(OAuth2Token.class); firstValidator.validate(token); secondValidator.validate(token); verify(firstSuccess, times(2)).validate(token); verify(secondSuccess, times(2)).validate(token); } }
5,510
46.508621
114
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthenticationMethodTests.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.oauth2.core; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuthenticationMethod}. * * @author MyeongHyeon Lee */ public class AuthenticationMethodTests { @Test public void constructorWhenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationMethod(null)) .withMessage("value cannot be empty"); } @Test public void getValueWhenHeaderAuthenticationTypeThenReturnHeader() { assertThat(AuthenticationMethod.HEADER.getValue()).isEqualTo("header"); } @Test public void getValueWhenFormAuthenticationTypeThenReturnForm() { assertThat(AuthenticationMethod.FORM.getValue()).isEqualTo("form"); } @Test public void getValueWhenFormAuthenticationTypeThenReturnQuery() { assertThat(AuthenticationMethod.QUERY.getValue()).isEqualTo("query"); } }
1,647
30.09434
87
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/TestOAuth2RefreshTokens.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.oauth2.core; import java.time.Instant; /** * @author Rob Winch * @since 5.1 */ public final class TestOAuth2RefreshTokens { private TestOAuth2RefreshTokens() { } public static OAuth2RefreshToken refreshToken() { return new OAuth2RefreshToken("refresh-token", Instant.now()); } }
953
26.257143
75
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2AccessTokenTests.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.oauth2.core; import java.time.Instant; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.util.SerializationUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AccessToken}. * * @author Joe Grandja */ public class OAuth2AccessTokenTests { private static final OAuth2AccessToken.TokenType TOKEN_TYPE = OAuth2AccessToken.TokenType.BEARER; private static final String TOKEN_VALUE = "access-token"; private static final Instant ISSUED_AT = Instant.now(); private static final Instant EXPIRES_AT = Instant.from(ISSUED_AT).plusSeconds(60); private static final Set<String> SCOPES = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); @Test public void tokenTypeGetValueWhenTokenTypeBearerThenReturnBearer() { assertThat(OAuth2AccessToken.TokenType.BEARER.getValue()).isEqualTo("Bearer"); } @Test public void constructorWhenTokenTypeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2AccessToken(null, TOKEN_VALUE, ISSUED_AT, EXPIRES_AT)); } @Test public void constructorWhenTokenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2AccessToken(TOKEN_TYPE, null, ISSUED_AT, EXPIRES_AT)); } @Test public void constructorWhenIssuedAtAfterExpiresAtThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AccessToken(TOKEN_TYPE, TOKEN_VALUE, Instant.from(EXPIRES_AT).plusSeconds(1), EXPIRES_AT)); } @Test public void constructorWhenExpiresAtBeforeIssuedAtThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AccessToken(TOKEN_TYPE, TOKEN_VALUE, ISSUED_AT, Instant.from(ISSUED_AT).minusSeconds(1))); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OAuth2AccessToken accessToken = new OAuth2AccessToken(TOKEN_TYPE, TOKEN_VALUE, ISSUED_AT, EXPIRES_AT, SCOPES); assertThat(accessToken.getTokenType()).isEqualTo(TOKEN_TYPE); assertThat(accessToken.getTokenValue()).isEqualTo(TOKEN_VALUE); assertThat(accessToken.getIssuedAt()).isEqualTo(ISSUED_AT); assertThat(accessToken.getExpiresAt()).isEqualTo(EXPIRES_AT); assertThat(accessToken.getScopes()).isEqualTo(SCOPES); } // gh-5492 @Test public void constructorWhenCreatedThenIsSerializableAndDeserializable() { OAuth2AccessToken accessToken = new OAuth2AccessToken(TOKEN_TYPE, TOKEN_VALUE, ISSUED_AT, EXPIRES_AT, SCOPES); byte[] serialized = SerializationUtils.serialize(accessToken); accessToken = (OAuth2AccessToken) SerializationUtils.deserialize(serialized); assertThat(serialized).isNotNull(); assertThat(accessToken.getTokenType()).isEqualTo(TOKEN_TYPE); assertThat(accessToken.getTokenValue()).isEqualTo(TOKEN_VALUE); assertThat(accessToken.getIssuedAt()).isEqualTo(ISSUED_AT); assertThat(accessToken.getExpiresAt()).isEqualTo(EXPIRES_AT); assertThat(accessToken.getScopes()).isEqualTo(SCOPES); } }
3,867
36.921569
113
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/TestOAuth2AccessTokens.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.oauth2.core; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.HashSet; /** * @author Rob Winch * @since 5.1 */ public final class TestOAuth2AccessTokens { private TestOAuth2AccessTokens() { } public static OAuth2AccessToken noScopes() { return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "no-scopes", Instant.now(), Instant.now().plus(Duration.ofDays(1))); } public static OAuth2AccessToken scopes(String... scopes) { return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "scopes", Instant.now(), Instant.now().plus(Duration.ofDays(1)), new HashSet<>(Arrays.asList(scopes))); } }
1,338
29.431818
94
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2TokenValidatorResultTests.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.oauth2.core; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for verifying {@link OAuth2TokenValidatorResult} * * @author Josh Cummings */ public class OAuth2TokenValidatorResultTests { private static final OAuth2Error DETAIL = new OAuth2Error("error", "description", "uri"); @Test public void successWhenInvokedThenReturnsSuccessfulResult() { OAuth2TokenValidatorResult success = OAuth2TokenValidatorResult.success(); assertThat(success.hasErrors()).isFalse(); } @Test public void failureWhenInvokedWithDetailReturnsFailureResultIncludingDetail() { OAuth2TokenValidatorResult failure = OAuth2TokenValidatorResult.failure(DETAIL); assertThat(failure.hasErrors()).isTrue(); assertThat(failure.getErrors()).containsExactly(DETAIL); } @Test public void failureWhenInvokedWithMultipleDetailsReturnsFailureResultIncludingAll() { OAuth2TokenValidatorResult failure = OAuth2TokenValidatorResult.failure(DETAIL, DETAIL); assertThat(failure.hasErrors()).isTrue(); assertThat(failure.getErrors()).containsExactly(DETAIL, DETAIL); } }
1,779
32.584906
90
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2RefreshTokenTests.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.oauth2.core; import java.time.Instant; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2RefreshToken}. * * @author Alexey Nesterov */ public class OAuth2RefreshTokenTests { private static final String TOKEN_VALUE = "refresh-token"; private static final Instant ISSUED_AT = Instant.now(); private static final Instant EXPIRES_AT = Instant.from(ISSUED_AT).plusSeconds(60); @Test public void constructorWhenTokenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2RefreshToken(null, ISSUED_AT, EXPIRES_AT)) .withMessage("tokenValue cannot be empty"); } @Test public void constructorWhenIssuedAtAfterExpiresAtThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy( () -> new OAuth2RefreshToken(TOKEN_VALUE, Instant.from(EXPIRES_AT).plusSeconds(1), EXPIRES_AT)) .withMessage("expiresAt must be after issuedAt"); } @Test public void constructorWhenExpiresAtBeforeIssuedAtThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy( () -> new OAuth2RefreshToken(TOKEN_VALUE, ISSUED_AT, Instant.from(ISSUED_AT).minusSeconds(1))) .withMessage("expiresAt must be after issuedAt"); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OAuth2RefreshToken token = new OAuth2RefreshToken(TOKEN_VALUE, ISSUED_AT, EXPIRES_AT); assertThat(token.getTokenValue()).isEqualTo(TOKEN_VALUE); assertThat(token.getIssuedAt()).isEqualTo(ISSUED_AT); assertThat(token.getExpiresAt()).isEqualTo(EXPIRES_AT); } }
2,422
33.614286
108
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthorizationGrantTypeTests.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.oauth2.core; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuthorizationGrantType}. * * @author Joe Grandja */ public class AuthorizationGrantTypeTests { @Test public void constructorWhenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizationGrantType(null)); } @Test public void getValueWhenAuthorizationCodeGrantTypeThenReturnAuthorizationCode() { assertThat(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()).isEqualTo("authorization_code"); } @Test public void getValueWhenRefreshTokenGrantTypeThenReturnRefreshToken() { assertThat(AuthorizationGrantType.REFRESH_TOKEN.getValue()).isEqualTo("refresh_token"); } @Test public void getValueWhenPasswordGrantTypeThenReturnPassword() { assertThat(AuthorizationGrantType.PASSWORD.getValue()).isEqualTo("password"); } @Test public void getValueWhenJwtBearerGrantTypeThenReturnJwtBearer() { assertThat(AuthorizationGrantType.JWT_BEARER.getValue()) .isEqualTo("urn:ietf:params:oauth:grant-type:jwt-bearer"); } }
1,879
31.413793
99
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2ErrorTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2Error}. * * @author Joe Grandja */ public class OAuth2ErrorTests { private static final String ERROR_CODE = "error-code"; private static final String ERROR_DESCRIPTION = "error-description"; private static final String ERROR_URI = "error-uri"; @Test public void constructorWhenErrorCodeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2Error(null, ERROR_DESCRIPTION, ERROR_URI)); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OAuth2Error error = new OAuth2Error(ERROR_CODE, ERROR_DESCRIPTION, ERROR_URI); assertThat(error.getErrorCode()).isEqualTo(ERROR_CODE); assertThat(error.getDescription()).isEqualTo(ERROR_DESCRIPTION); assertThat(error.getUri()).isEqualTo(ERROR_URI); } }
1,680
31.960784
109
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractorsTests.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.oauth2.core.web.reactive.function; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.core.codec.ByteBufferDecoder; import org.springframework.core.codec.StringDecoder; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpInputMessage; import org.springframework.http.codec.DecoderHttpMessageReader; import org.springframework.http.codec.FormHttpMessageReader; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.mock.http.client.reactive.MockClientHttpResponse; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.web.reactive.function.BodyExtractor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch * @since 5.1 */ public class OAuth2BodyExtractorsTests { private BodyExtractor.Context context; private Map<String, Object> hints; @BeforeEach public void createContext() { final List<HttpMessageReader<?>> messageReaders = new ArrayList<>(); messageReaders.add(new DecoderHttpMessageReader<>(new ByteBufferDecoder())); messageReaders.add(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes())); messageReaders.add(new DecoderHttpMessageReader<>(new Jackson2JsonDecoder())); messageReaders.add(new FormHttpMessageReader()); this.hints = new HashMap<>(); this.context = new BodyExtractor.Context() { @Override public List<HttpMessageReader<?>> messageReaders() { return messageReaders; } @Override public Optional<ServerHttpResponse> serverResponse() { return Optional.empty(); } @Override public Map<String, Object> hints() { return OAuth2BodyExtractorsTests.this.hints; } }; } @Test public void oauth2AccessTokenResponseWhenInvalidJsonThenException() { BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = OAuth2BodyExtractors .oauth2AccessTokenResponse(); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.setBody("{"); Mono<OAuth2AccessTokenResponse> result = extractor.extract(response, this.context); // @formatter:off assertThatExceptionOfType(OAuth2AuthorizationException.class) .isThrownBy(result::block) .withMessageContaining("An error occurred parsing the Access Token response"); // @formatter:on } @Test public void oauth2AccessTokenResponseWhenEmptyThenException() { BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = OAuth2BodyExtractors .oauth2AccessTokenResponse(); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); Mono<OAuth2AccessTokenResponse> result = extractor.extract(response, this.context); // @formatter:off assertThatExceptionOfType(OAuth2AuthorizationException.class) .isThrownBy(result::block) .withMessageContaining("Empty OAuth 2.0 Access Token Response"); // @formatter:on } @Test public void oauth2AccessTokenResponseWhenValidThenCreated() { BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = OAuth2BodyExtractors .oauth2AccessTokenResponse(); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); // @formatter:off response.setBody( "{\n" + " \"access_token\":\"2YotnFZFEjr1zCsicMWpAA\",\n" + " \"token_type\":\"Bearer\",\n" + " \"expires_in\":3600,\n" + " \"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\",\n" + " \"example_parameter\":\"example_value\"\n" + " }"); // @formatter:on Instant now = Instant.now(); OAuth2AccessTokenResponse result = extractor.extract(response, this.context).block(); assertThat(result.getAccessToken().getTokenValue()).isEqualTo("2YotnFZFEjr1zCsicMWpAA"); assertThat(result.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(result.getAccessToken().getExpiresAt()).isBetween(now.plusSeconds(3600), now.plusSeconds(3600 + 2)); assertThat(result.getRefreshToken().getTokenValue()).isEqualTo("tGzv3JOkF0XG5Qx2TlKWIA"); assertThat(result.getAdditionalParameters()).containsEntry("example_parameter", "example_value"); } @Test // gh-6087 public void oauth2AccessTokenResponseWhenMultipleAttributeTypesThenCreated() { BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = OAuth2BodyExtractors .oauth2AccessTokenResponse(); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); // @formatter:off response.setBody( "{\n" + " \"access_token\":\"2YotnFZFEjr1zCsicMWpAA\",\n" + " \"token_type\":\"Bearer\",\n" + " \"expires_in\":3600,\n" + " \"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\",\n" + " \"subjson\":{}, \n" + " \"list\":[] \n" + " }"); // @formatter:on Instant now = Instant.now(); OAuth2AccessTokenResponse result = extractor.extract(response, this.context).block(); assertThat(result.getAccessToken().getTokenValue()).isEqualTo("2YotnFZFEjr1zCsicMWpAA"); assertThat(result.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(result.getAccessToken().getExpiresAt()).isBetween(now.plusSeconds(3600), now.plusSeconds(3600 + 2)); assertThat(result.getRefreshToken().getTokenValue()).isEqualTo("tGzv3JOkF0XG5Qx2TlKWIA"); assertThat(result.getAdditionalParameters().get("subjson")).isInstanceOfAny(Map.class); assertThat(result.getAdditionalParameters().get("list")).isInstanceOfAny(List.class); } }
7,054
41.245509
113
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/user/DefaultOAuth2UserTests.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.oauth2.core.user; import java.util.Collections; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.util.SerializationUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultOAuth2User}. * * @author Vedran Pavic * @author Joe Grandja */ public class DefaultOAuth2UserTests { private static final SimpleGrantedAuthority AUTHORITY = new SimpleGrantedAuthority("ROLE_USER"); private static final Set<GrantedAuthority> AUTHORITIES = Collections.singleton(AUTHORITY); private static final String ATTRIBUTE_NAME_KEY = "username"; private static final String USERNAME = "test"; private static final Map<String, Object> ATTRIBUTES = Collections.singletonMap(ATTRIBUTE_NAME_KEY, USERNAME); @Test public void constructorWhenAttributesIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, null, ATTRIBUTE_NAME_KEY)); } @Test public void constructorWhenAttributesIsEmptyThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, Collections.emptyMap(), ATTRIBUTE_NAME_KEY)); } @Test public void constructorWhenNameAttributeKeyIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, null)); } @Test public void constructorWhenNameAttributeKeyIsInvalidThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, "invalid")); } @Test public void constructorWhenAuthoritiesIsNullThenCreatedWithEmptyAuthorities() { DefaultOAuth2User user = new DefaultOAuth2User(null, ATTRIBUTES, ATTRIBUTE_NAME_KEY); assertThat(user.getName()).isEqualTo(USERNAME); assertThat(user.getAuthorities()).isEmpty(); assertThat(user.getAttributes()).containsOnlyKeys(ATTRIBUTE_NAME_KEY); } @Test public void constructorWhenAuthoritiesIsEmptyThenCreated() { DefaultOAuth2User user = new DefaultOAuth2User(Collections.emptySet(), ATTRIBUTES, ATTRIBUTE_NAME_KEY); assertThat(user.getName()).isEqualTo(USERNAME); assertThat(user.getAuthorities()).isEmpty(); assertThat(user.getAttributes()).containsOnlyKeys(ATTRIBUTE_NAME_KEY); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { DefaultOAuth2User user = new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, ATTRIBUTE_NAME_KEY); assertThat(user.getName()).isEqualTo(USERNAME); assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY); assertThat(user.getAttributes()).containsOnlyKeys(ATTRIBUTE_NAME_KEY); } // gh-4917 @Test public void constructorWhenCreatedThenIsSerializable() { DefaultOAuth2User user = new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, ATTRIBUTE_NAME_KEY); SerializationUtils.serialize(user); } }
3,898
35.783019
110
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/user/TestOAuth2Users.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.oauth2.core.user; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; /** * @author Rob Winch */ public final class TestOAuth2Users { private TestOAuth2Users() { } public static DefaultOAuth2User create() { String nameAttributeKey = "username"; Map<String, Object> attributes = new HashMap<>(); attributes.put(nameAttributeKey, "user"); Collection<GrantedAuthority> authorities = authorities(attributes); return new DefaultOAuth2User(authorities, attributes, nameAttributeKey); } private static Collection<GrantedAuthority> authorities(Map<String, Object> attributes) { return new LinkedHashSet<>(Arrays.asList(new OAuth2UserAuthority(attributes), new SimpleGrantedAuthority("SCOPE_read"), new SimpleGrantedAuthority("SCOPE_write"))); } }
1,646
31.94
90
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/user/OAuth2UserAuthorityTests.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.oauth2.core.user; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2UserAuthority}. * * @author Joe Grandja */ public class OAuth2UserAuthorityTests { private static final String AUTHORITY = "ROLE_USER"; private static final Map<String, Object> ATTRIBUTES = Collections.singletonMap("username", "test"); private static final OAuth2UserAuthority AUTHORITY_WITH_OBJECTURL; private static final OAuth2UserAuthority AUTHORITY_WITH_STRINGURL; static { try { AUTHORITY_WITH_OBJECTURL = new OAuth2UserAuthority( Collections.singletonMap("someurl", new URL("https://localhost"))); AUTHORITY_WITH_STRINGURL = new OAuth2UserAuthority( Collections.singletonMap("someurl", "https://localhost")); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } } @Test public void constructorWhenAuthorityIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserAuthority(null, ATTRIBUTES)); } @Test public void constructorWhenAttributesIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserAuthority(AUTHORITY, null)); } @Test public void constructorWhenAttributesIsEmptyThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2UserAuthority(AUTHORITY, Collections.emptyMap())); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OAuth2UserAuthority userAuthority = new OAuth2UserAuthority(AUTHORITY, ATTRIBUTES); assertThat(userAuthority.getAuthority()).isEqualTo(AUTHORITY); assertThat(userAuthority.getAttributes()).isEqualTo(ATTRIBUTES); } @Test public void equalsRegardlessOfUrlType() { assertThat(AUTHORITY_WITH_OBJECTURL).isEqualTo(AUTHORITY_WITH_OBJECTURL); assertThat(AUTHORITY_WITH_STRINGURL).isEqualTo(AUTHORITY_WITH_STRINGURL); assertThat(AUTHORITY_WITH_OBJECTURL).isEqualTo(AUTHORITY_WITH_STRINGURL); assertThat(AUTHORITY_WITH_STRINGURL).isEqualTo(AUTHORITY_WITH_OBJECTURL); } @Test public void hashCodeIsSameRegardlessOfUrlType() { assertThat(AUTHORITY_WITH_OBJECTURL.hashCode()).isEqualTo(AUTHORITY_WITH_OBJECTURL.hashCode()); assertThat(AUTHORITY_WITH_STRINGURL.hashCode()).isEqualTo(AUTHORITY_WITH_STRINGURL.hashCode()); assertThat(AUTHORITY_WITH_OBJECTURL.hashCode()).isEqualTo(AUTHORITY_WITH_STRINGURL.hashCode()); assertThat(AUTHORITY_WITH_STRINGURL.hashCode()).isEqualTo(AUTHORITY_WITH_OBJECTURL.hashCode()); } }
3,448
34.193878
100
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimConversionServiceTests.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.oauth2.core.converter; import java.net.URL; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.springframework.core.convert.ConversionService; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ClaimConversionService}. * * @author Joe Grandja * @since 5.2 */ public class ClaimConversionServiceTests { private final ConversionService conversionService = ClaimConversionService.getSharedInstance(); @Test public void convertStringWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, String.class)).isNull(); } @Test public void convertStringWhenStringThenReturnSame() { assertThat(this.conversionService.convert("string", String.class)).isSameAs("string"); } @Test public void convertStringWhenNumberThenConverts() { assertThat(this.conversionService.convert(1234, String.class)).isEqualTo("1234"); } @Test public void convertBooleanWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, Boolean.class)).isNull(); } @Test public void convertBooleanWhenBooleanThenReturnSame() { assertThat(this.conversionService.convert(Boolean.TRUE, Boolean.class)).isSameAs(Boolean.TRUE); } @Test public void convertBooleanWhenStringTrueThenConverts() { assertThat(this.conversionService.convert("true", Boolean.class)).isEqualTo(Boolean.TRUE); } @Test public void convertBooleanWhenNotConvertibleThenReturnBooleanFalse() { assertThat(this.conversionService.convert("not-convertible-boolean", Boolean.class)).isEqualTo(Boolean.FALSE); } @Test public void convertInstantWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, Instant.class)).isNull(); } @Test public void convertInstantWhenInstantThenReturnSame() { Instant instant = Instant.now(); assertThat(this.conversionService.convert(instant, Instant.class)).isSameAs(instant); } @Test public void convertInstantWhenDateThenConverts() { Instant instant = new Date().toInstant(); assertThat(this.conversionService.convert(Date.from(instant), Instant.class)).isEqualTo(instant); } @Test public void convertInstantWhenNumberThenConverts() { Instant instant = Instant.now(); assertThat(this.conversionService.convert(instant.getEpochSecond(), Instant.class)) .isEqualTo(instant.truncatedTo(ChronoUnit.SECONDS)); } @Test public void convertInstantWhenStringThenConverts() { Instant instant = Instant.now(); assertThat(this.conversionService.convert(String.valueOf(instant.getEpochSecond()), Instant.class)) .isEqualTo(instant.truncatedTo(ChronoUnit.SECONDS)); assertThat(this.conversionService.convert(String.valueOf(instant.toString()), Instant.class)) .isEqualTo(instant); } @Test public void convertInstantWhenNotConvertibleThenReturnNull() { assertThat(this.conversionService.convert("not-convertible-instant", Instant.class)).isNull(); } @Test public void convertUrlWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, URL.class)).isNull(); } @Test public void convertUrlWhenUrlThenReturnSame() throws Exception { URL url = new URL("https://localhost"); assertThat(this.conversionService.convert(url, URL.class)).isSameAs(url); } @Test public void convertUrlWhenStringThenConverts() throws Exception { String urlString = "https://localhost"; URL url = new URL(urlString); assertThat(this.conversionService.convert(urlString, URL.class)).isEqualTo(url); } @Test public void convertUrlWhenNotConvertibleThenReturnNull() { assertThat(this.conversionService.convert("not-convertible-url", URL.class)).isNull(); } @Test public void convertCollectionStringWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, Collection.class)).isNull(); } @Test public void convertCollectionStringWhenListStringThenReturnNotSameButEqual() { List<String> list = Lists.list("1", "2", "3", "4"); assertThat(this.conversionService.convert(list, Collection.class)).isNotSameAs(list).isEqualTo(list); } @Test public void convertCollectionStringWhenListNumberThenConverts() { assertThat(this.conversionService.convert(Lists.list(1, 2, 3, 4), Collection.class)) .isEqualTo(Lists.list("1", "2", "3", "4")); } @Test public void convertListStringWhenJsonArrayThenConverts() { JSONArray jsonArray = new JSONArray(); jsonArray.add("1"); jsonArray.add("2"); jsonArray.add("3"); jsonArray.add(null); assertThat(this.conversionService.convert(jsonArray, List.class)).isNotInstanceOf(JSONArray.class) .isEqualTo(Lists.list("1", "2", "3")); } @Test public void convertCollectionStringWhenNotConvertibleThenReturnSingletonList() { String string = "not-convertible-collection"; assertThat(this.conversionService.convert(string, Collection.class)) .isEqualTo(Collections.singletonList(string)); } @Test public void convertListStringWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, List.class)).isNull(); } @Test public void convertListStringWhenListStringThenReturnNotSameButEqual() { List<String> list = Lists.list("1", "2", "3", "4"); assertThat(this.conversionService.convert(list, List.class)).isNotSameAs(list).isEqualTo(list); } @Test public void convertListStringWhenListNumberThenConverts() { assertThat(this.conversionService.convert(Lists.list(1, 2, 3, 4), List.class)) .isEqualTo(Lists.list("1", "2", "3", "4")); } @Test public void convertListStringWhenNotConvertibleThenReturnSingletonList() { String string = "not-convertible-list"; assertThat(this.conversionService.convert(string, List.class)).isEqualTo(Collections.singletonList(string)); } @Test public void convertMapStringObjectWhenNullThenReturnNull() { assertThat(this.conversionService.convert(null, Map.class)).isNull(); } @Test public void convertMapStringObjectWhenMapStringObjectThenReturnNotSameButEqual() { Map<String, Object> mapStringObject = new HashMap<String, Object>() { { put("key1", "value1"); put("key2", "value2"); put("key3", "value3"); } }; assertThat(this.conversionService.convert(mapStringObject, Map.class)).isNotSameAs(mapStringObject) .isEqualTo(mapStringObject); } @Test public void convertMapStringObjectWhenMapIntegerObjectThenConverts() { Map<String, Object> mapStringObject = new HashMap<String, Object>() { { put("1", "value1"); put("2", "value2"); put("3", "value3"); } }; Map<Integer, Object> mapIntegerObject = new HashMap<Integer, Object>() { { put(1, "value1"); put(2, "value2"); put(3, "value3"); } }; assertThat(this.conversionService.convert(mapIntegerObject, Map.class)).isEqualTo(mapStringObject); } @Test public void convertMapStringObjectWhenJsonObjectThenConverts() { JSONObject jsonObject = new JSONObject(); jsonObject.put("1", "value1"); jsonObject.put("2", "value2"); Map<String, Object> mapStringObject = new HashMap<String, Object>() { { put("1", "value1"); put("2", "value2"); } }; assertThat(this.conversionService.convert(jsonObject, Map.class)).isNotInstanceOf(JSONObject.class) .isEqualTo(mapStringObject); } @Test public void convertMapStringObjectWhenNotConvertibleThenReturnNull() { List<String> notConvertibleList = Lists.list("1", "2", "3", "4"); assertThat(this.conversionService.convert(notConvertibleList, Map.class)).isNull(); } }
8,366
30.935115
112
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverterTests.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.oauth2.core.converter; import java.net.URL; import java.time.Instant; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import org.assertj.core.util.Lists; import org.assertj.core.util.Maps; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClaimTypeConverter}. * * @author Joe Grandja * @since 5.2 */ public class ClaimTypeConverterTests { private static final String STRING_CLAIM = "string-claim"; private static final String BOOLEAN_CLAIM = "boolean-claim"; private static final String INSTANT_CLAIM = "instant-claim"; private static final String URL_CLAIM = "url-claim"; private static final String COLLECTION_STRING_CLAIM = "collection-string-claim"; private static final String LIST_STRING_CLAIM = "list-string-claim"; private static final String MAP_STRING_OBJECT_CLAIM = "map-string-object-claim"; private static final String JSON_ARRAY_CLAIM = "json-array-claim"; private static final String JSON_OBJECT_CLAIM = "json-object-claim"; private ClaimTypeConverter claimTypeConverter; @BeforeEach @SuppressWarnings("unchecked") public void setup() { Converter<Object, ?> stringConverter = getConverter(TypeDescriptor.valueOf(String.class)); Converter<Object, ?> booleanConverter = getConverter(TypeDescriptor.valueOf(Boolean.class)); Converter<Object, ?> instantConverter = getConverter(TypeDescriptor.valueOf(Instant.class)); Converter<Object, ?> urlConverter = getConverter(TypeDescriptor.valueOf(URL.class)); Converter<Object, ?> collectionStringConverter = getConverter( TypeDescriptor.collection(Collection.class, TypeDescriptor.valueOf(String.class))); Converter<Object, ?> listStringConverter = getConverter( TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(String.class))); Converter<Object, ?> mapStringObjectConverter = getConverter(TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Object.class))); Map<String, Converter<Object, ?>> claimTypeConverters = new HashMap<>(); claimTypeConverters.put(STRING_CLAIM, stringConverter); claimTypeConverters.put(BOOLEAN_CLAIM, booleanConverter); claimTypeConverters.put(INSTANT_CLAIM, instantConverter); claimTypeConverters.put(URL_CLAIM, urlConverter); claimTypeConverters.put(COLLECTION_STRING_CLAIM, collectionStringConverter); claimTypeConverters.put(LIST_STRING_CLAIM, listStringConverter); claimTypeConverters.put(MAP_STRING_OBJECT_CLAIM, mapStringObjectConverter); this.claimTypeConverter = new ClaimTypeConverter(claimTypeConverters); } private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) { final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class); return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor, targetDescriptor); } @Test public void constructorWhenConvertersNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new ClaimTypeConverter(null)); } @Test public void constructorWhenConvertersHasNullConverterThenThrowIllegalArgumentException() { Map<String, Converter<Object, ?>> claimTypeConverters = new HashMap<>(); claimTypeConverters.put("claim1", null); assertThatIllegalArgumentException().isThrownBy(() -> new ClaimTypeConverter(claimTypeConverters)); } @Test public void convertWhenClaimsEmptyThenReturnSame() { Map<String, Object> claims = new HashMap<>(); assertThat(this.claimTypeConverter.convert(claims)).isSameAs(claims); } @Test public void convertWhenAllClaimsRequireConversionThenConvertAll() throws Exception { Instant instant = Instant.now(); URL url = new URL("https://localhost"); List<Number> listNumber = Lists.list(1, 2, 3, 4); List<String> listString = Lists.list("1", "2", "3", "4"); Map<Integer, Object> mapIntegerObject = new HashMap<>(); mapIntegerObject.put(1, "value1"); Map<String, Object> mapStringObject = new HashMap<>(); mapStringObject.put("1", "value1"); JSONArray jsonArray = new JSONArray(); jsonArray.add("1"); List<String> jsonArrayListString = Lists.list("1"); JSONObject jsonObject = new JSONObject(); jsonObject.put("1", "value1"); Map<String, Object> jsonObjectMap = Maps.newHashMap("1", "value1"); Map<String, Object> claims = new HashMap<>(); claims.put(STRING_CLAIM, Boolean.TRUE); claims.put(BOOLEAN_CLAIM, "true"); claims.put(INSTANT_CLAIM, instant.toString()); claims.put(URL_CLAIM, url.toExternalForm()); claims.put(COLLECTION_STRING_CLAIM, listNumber); claims.put(LIST_STRING_CLAIM, listNumber); claims.put(MAP_STRING_OBJECT_CLAIM, mapIntegerObject); claims.put(JSON_ARRAY_CLAIM, jsonArray); claims.put(JSON_OBJECT_CLAIM, jsonObject); claims = this.claimTypeConverter.convert(claims); assertThat(claims.get(STRING_CLAIM)).isEqualTo("true"); assertThat(claims.get(BOOLEAN_CLAIM)).isEqualTo(Boolean.TRUE); assertThat(claims.get(INSTANT_CLAIM)).isEqualTo(instant); assertThat(claims.get(URL_CLAIM)).isEqualTo(url); assertThat(claims.get(COLLECTION_STRING_CLAIM)).isEqualTo(listString); assertThat(claims.get(LIST_STRING_CLAIM)).isEqualTo(listString); assertThat(claims.get(MAP_STRING_OBJECT_CLAIM)).isEqualTo(mapStringObject); assertThat(claims.get(JSON_ARRAY_CLAIM)).isEqualTo(jsonArrayListString); assertThat(claims.get(JSON_OBJECT_CLAIM)).isEqualTo(jsonObjectMap); } @Test public void convertWhenNoClaimsRequireConversionThenConvertNone() throws Exception { String string = "value"; Boolean bool = Boolean.TRUE; Instant instant = Instant.now(); URL url = new URL("https://localhost"); List<String> listString = Lists.list("1", "2", "3", "4"); Map<String, Object> mapStringObject = new HashMap<>(); mapStringObject.put("1", "value1"); Map<String, Object> claims = new HashMap<>(); claims.put(STRING_CLAIM, string); claims.put(BOOLEAN_CLAIM, bool); claims.put(INSTANT_CLAIM, instant); claims.put(URL_CLAIM, url); claims.put(COLLECTION_STRING_CLAIM, listString); claims.put(LIST_STRING_CLAIM, listString); claims.put(MAP_STRING_OBJECT_CLAIM, mapStringObject); claims = this.claimTypeConverter.convert(claims); assertThat(claims.get(STRING_CLAIM)).isSameAs(string); assertThat(claims.get(BOOLEAN_CLAIM)).isSameAs(bool); assertThat(claims.get(INSTANT_CLAIM)).isSameAs(instant); assertThat(claims.get(URL_CLAIM)).isSameAs(url); assertThat(claims.get(COLLECTION_STRING_CLAIM)).isNotSameAs(listString).isEqualTo(listString); assertThat(claims.get(LIST_STRING_CLAIM)).isNotSameAs(listString).isEqualTo(listString); assertThat(claims.get(MAP_STRING_OBJECT_CLAIM)).isNotSameAs(mapStringObject).isEqualTo(mapStringObject); } @Test public void convertWhenConverterNotAvailableThenDoesNotConvert() { Map<String, Object> claims = new HashMap<>(); claims.put("claim1", "value1"); claims = this.claimTypeConverter.convert(claims); assertThat(claims.get("claim1")).isSameAs("value1"); } }
8,017
41.42328
106
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.oidc; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcUserInfo}. * * @author Joe Grandja */ public class OidcUserInfoTests { private static final String SUB_CLAIM = "sub"; private static final String NAME_CLAIM = "name"; private static final String GIVEN_NAME_CLAIM = "given_name"; private static final String FAMILY_NAME_CLAIM = "family_name"; private static final String MIDDLE_NAME_CLAIM = "middle_name"; private static final String NICKNAME_CLAIM = "nickname"; private static final String PREFERRED_USERNAME_CLAIM = "preferred_username"; private static final String PROFILE_CLAIM = "profile"; private static final String PICTURE_CLAIM = "picture"; private static final String WEBSITE_CLAIM = "website"; private static final String EMAIL_CLAIM = "email"; private static final String EMAIL_VERIFIED_CLAIM = "email_verified"; private static final String GENDER_CLAIM = "gender"; private static final String BIRTHDATE_CLAIM = "birthdate"; private static final String ZONEINFO_CLAIM = "zoneinfo"; private static final String LOCALE_CLAIM = "locale"; private static final String PHONE_NUMBER_CLAIM = "phone_number"; private static final String PHONE_NUMBER_VERIFIED_CLAIM = "phone_number_verified"; private static final String ADDRESS_CLAIM = "address"; private static final String UPDATED_AT_CLAIM = "updated_at"; private static final String SUB_VALUE = "subject1"; private static final String NAME_VALUE = "full_name"; private static final String GIVEN_NAME_VALUE = "given_name"; private static final String FAMILY_NAME_VALUE = "family_name"; private static final String MIDDLE_NAME_VALUE = "middle_name"; private static final String NICKNAME_VALUE = "nickname"; private static final String PREFERRED_USERNAME_VALUE = "preferred_username"; private static final String PROFILE_VALUE = "profile"; private static final String PICTURE_VALUE = "picture"; private static final String WEBSITE_VALUE = "website"; private static final String EMAIL_VALUE = "email"; private static final Boolean EMAIL_VERIFIED_VALUE = true; private static final String GENDER_VALUE = "gender"; private static final String BIRTHDATE_VALUE = "birthdate"; private static final String ZONEINFO_VALUE = "zoneinfo"; private static final String LOCALE_VALUE = "locale"; private static final String PHONE_NUMBER_VALUE = "phone_number"; private static final Boolean PHONE_NUMBER_VERIFIED_VALUE = true; private static final Map<String, Object> ADDRESS_VALUE; private static final long UPDATED_AT_VALUE = Instant.now().minusSeconds(60).toEpochMilli(); private static final Map<String, Object> CLAIMS; static { CLAIMS = new HashMap<>(); CLAIMS.put(SUB_CLAIM, SUB_VALUE); CLAIMS.put(NAME_CLAIM, NAME_VALUE); CLAIMS.put(GIVEN_NAME_CLAIM, GIVEN_NAME_VALUE); CLAIMS.put(FAMILY_NAME_CLAIM, FAMILY_NAME_VALUE); CLAIMS.put(MIDDLE_NAME_CLAIM, MIDDLE_NAME_VALUE); CLAIMS.put(NICKNAME_CLAIM, NICKNAME_VALUE); CLAIMS.put(PREFERRED_USERNAME_CLAIM, PREFERRED_USERNAME_VALUE); CLAIMS.put(PROFILE_CLAIM, PROFILE_VALUE); CLAIMS.put(PICTURE_CLAIM, PICTURE_VALUE); CLAIMS.put(WEBSITE_CLAIM, WEBSITE_VALUE); CLAIMS.put(EMAIL_CLAIM, EMAIL_VALUE); CLAIMS.put(EMAIL_VERIFIED_CLAIM, EMAIL_VERIFIED_VALUE); CLAIMS.put(GENDER_CLAIM, GENDER_VALUE); CLAIMS.put(BIRTHDATE_CLAIM, BIRTHDATE_VALUE); CLAIMS.put(ZONEINFO_CLAIM, ZONEINFO_VALUE); CLAIMS.put(LOCALE_CLAIM, LOCALE_VALUE); CLAIMS.put(PHONE_NUMBER_CLAIM, PHONE_NUMBER_VALUE); CLAIMS.put(PHONE_NUMBER_VERIFIED_CLAIM, PHONE_NUMBER_VERIFIED_VALUE); ADDRESS_VALUE = new HashMap<>(); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.FORMATTED_FIELD_NAME, DefaultAddressStandardClaimTests.FORMATTED); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.STREET_ADDRESS_FIELD_NAME, DefaultAddressStandardClaimTests.STREET_ADDRESS); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.LOCALITY_FIELD_NAME, DefaultAddressStandardClaimTests.LOCALITY); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.REGION_FIELD_NAME, DefaultAddressStandardClaimTests.REGION); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.POSTAL_CODE_FIELD_NAME, DefaultAddressStandardClaimTests.POSTAL_CODE); ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.COUNTRY_FIELD_NAME, DefaultAddressStandardClaimTests.COUNTRY); CLAIMS.put(ADDRESS_CLAIM, ADDRESS_VALUE); CLAIMS.put(UPDATED_AT_CLAIM, UPDATED_AT_VALUE); } @Test public void constructorWhenClaimsIsEmptyThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OidcUserInfo(Collections.emptyMap())); } @Test public void constructorWhenParametersProvidedAndValidThenCreated() { OidcUserInfo userInfo = new OidcUserInfo(CLAIMS); assertThat(userInfo.getClaims()).isEqualTo(CLAIMS); assertThat(userInfo.getSubject()).isEqualTo(SUB_VALUE); assertThat(userInfo.getFullName()).isEqualTo(NAME_VALUE); assertThat(userInfo.getGivenName()).isEqualTo(GIVEN_NAME_VALUE); assertThat(userInfo.getFamilyName()).isEqualTo(FAMILY_NAME_VALUE); assertThat(userInfo.getMiddleName()).isEqualTo(MIDDLE_NAME_VALUE); assertThat(userInfo.getNickName()).isEqualTo(NICKNAME_VALUE); assertThat(userInfo.getPreferredUsername()).isEqualTo(PREFERRED_USERNAME_VALUE); assertThat(userInfo.getProfile()).isEqualTo(PROFILE_VALUE); assertThat(userInfo.getPicture()).isEqualTo(PICTURE_VALUE); assertThat(userInfo.getWebsite()).isEqualTo(WEBSITE_VALUE); assertThat(userInfo.getEmail()).isEqualTo(EMAIL_VALUE); assertThat(userInfo.getEmailVerified()).isEqualTo(EMAIL_VERIFIED_VALUE); assertThat(userInfo.getGender()).isEqualTo(GENDER_VALUE); assertThat(userInfo.getBirthdate()).isEqualTo(BIRTHDATE_VALUE); assertThat(userInfo.getZoneInfo()).isEqualTo(ZONEINFO_VALUE); assertThat(userInfo.getLocale()).isEqualTo(LOCALE_VALUE); assertThat(userInfo.getPhoneNumber()).isEqualTo(PHONE_NUMBER_VALUE); assertThat(userInfo.getPhoneNumberVerified()).isEqualTo(PHONE_NUMBER_VERIFIED_VALUE); assertThat(userInfo.getAddress()).isEqualTo(new DefaultAddressStandardClaim.Builder(ADDRESS_VALUE).build()); assertThat(userInfo.getUpdatedAt().getEpochSecond()).isEqualTo(UPDATED_AT_VALUE); } }
7,141
37.605405
113
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaimTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.oidc; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultAddressStandardClaim}. * * @author Joe Grandja */ public class DefaultAddressStandardClaimTests { static final String FORMATTED_FIELD_NAME = "formatted"; static final String STREET_ADDRESS_FIELD_NAME = "street_address"; static final String LOCALITY_FIELD_NAME = "locality"; static final String REGION_FIELD_NAME = "region"; static final String POSTAL_CODE_FIELD_NAME = "postal_code"; static final String COUNTRY_FIELD_NAME = "country"; static final String FORMATTED = "formatted"; static final String STREET_ADDRESS = "street_address"; static final String LOCALITY = "locality"; static final String REGION = "region"; static final String POSTAL_CODE = "postal_code"; static final String COUNTRY = "country"; @Test public void buildWhenAllAttributesProvidedThenAllAttributesAreSet() { // @formatter:off AddressStandardClaim addressStandardClaim = new DefaultAddressStandardClaim.Builder() .formatted(FORMATTED) .streetAddress(STREET_ADDRESS) .locality(LOCALITY) .region(REGION) .postalCode(POSTAL_CODE) .country(COUNTRY) .build(); // @formatter:on assertThat(addressStandardClaim.getFormatted()).isEqualTo(FORMATTED); assertThat(addressStandardClaim.getStreetAddress()).isEqualTo(STREET_ADDRESS); assertThat(addressStandardClaim.getLocality()).isEqualTo(LOCALITY); assertThat(addressStandardClaim.getRegion()).isEqualTo(REGION); assertThat(addressStandardClaim.getPostalCode()).isEqualTo(POSTAL_CODE); assertThat(addressStandardClaim.getCountry()).isEqualTo(COUNTRY); } @Test public void buildWhenAllAttributesProvidedToConstructorThenAllAttributesAreSet() { Map<String, Object> addressFields = new HashMap<>(); addressFields.put(FORMATTED_FIELD_NAME, FORMATTED); addressFields.put(STREET_ADDRESS_FIELD_NAME, STREET_ADDRESS); addressFields.put(LOCALITY_FIELD_NAME, LOCALITY); addressFields.put(REGION_FIELD_NAME, REGION); addressFields.put(POSTAL_CODE_FIELD_NAME, POSTAL_CODE); addressFields.put(COUNTRY_FIELD_NAME, COUNTRY); AddressStandardClaim addressStandardClaim = new DefaultAddressStandardClaim.Builder(addressFields).build(); assertThat(addressStandardClaim.getFormatted()).isEqualTo(FORMATTED); assertThat(addressStandardClaim.getStreetAddress()).isEqualTo(STREET_ADDRESS); assertThat(addressStandardClaim.getLocality()).isEqualTo(LOCALITY); assertThat(addressStandardClaim.getRegion()).isEqualTo(REGION); assertThat(addressStandardClaim.getPostalCode()).isEqualTo(POSTAL_CODE); assertThat(addressStandardClaim.getCountry()).isEqualTo(COUNTRY); } }
3,410
39.129412
109
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.oidc; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcIdToken}. * * @author Joe Grandja */ public class OidcIdTokenTests { private static final String ISS_CLAIM = "iss"; private static final String SUB_CLAIM = "sub"; private static final String AUD_CLAIM = "aud"; private static final String IAT_CLAIM = "iat"; private static final String EXP_CLAIM = "exp"; private static final String AUTH_TIME_CLAIM = "auth_time"; private static final String NONCE_CLAIM = "nonce"; private static final String ACR_CLAIM = "acr"; private static final String AMR_CLAIM = "amr"; private static final String AZP_CLAIM = "azp"; private static final String AT_HASH_CLAIM = "at_hash"; private static final String C_HASH_CLAIM = "c_hash"; private static final String ISS_VALUE = "https://provider.com"; private static final String SUB_VALUE = "subject1"; private static final List<String> AUD_VALUE = Arrays.asList("aud1", "aud2"); private static final long IAT_VALUE = Instant.now().toEpochMilli(); private static final long EXP_VALUE = Instant.now().plusSeconds(60).toEpochMilli(); private static final long AUTH_TIME_VALUE = Instant.now().minusSeconds(5).toEpochMilli(); private static final String NONCE_VALUE = "nonce"; private static final String ACR_VALUE = "acr"; private static final List<String> AMR_VALUE = Arrays.asList("amr1", "amr2"); private static final String AZP_VALUE = "azp"; private static final String AT_HASH_VALUE = "at_hash"; private static final String C_HASH_VALUE = "c_hash"; private static final Map<String, Object> CLAIMS; private static final String ID_TOKEN_VALUE = "id-token-value"; static { CLAIMS = new HashMap<>(); CLAIMS.put(ISS_CLAIM, ISS_VALUE); CLAIMS.put(SUB_CLAIM, SUB_VALUE); CLAIMS.put(AUD_CLAIM, AUD_VALUE); CLAIMS.put(IAT_CLAIM, IAT_VALUE); CLAIMS.put(EXP_CLAIM, EXP_VALUE); CLAIMS.put(AUTH_TIME_CLAIM, AUTH_TIME_VALUE); CLAIMS.put(NONCE_CLAIM, NONCE_VALUE); CLAIMS.put(ACR_CLAIM, ACR_VALUE); CLAIMS.put(AMR_CLAIM, AMR_VALUE); CLAIMS.put(AZP_CLAIM, AZP_VALUE); CLAIMS.put(AT_HASH_CLAIM, AT_HASH_VALUE); CLAIMS.put(C_HASH_CLAIM, C_HASH_VALUE); } @Test public void constructorWhenTokenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new OidcIdToken(null, Instant.ofEpochMilli(IAT_VALUE), Instant.ofEpochMilli(EXP_VALUE), CLAIMS)); } @Test public void constructorWhenClaimsIsEmptyThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OidcIdToken(ID_TOKEN_VALUE, Instant.ofEpochMilli(IAT_VALUE), Instant.ofEpochMilli(EXP_VALUE), Collections.emptyMap())); } @Test public void constructorWhenParametersProvidedAndValidThenCreated() { OidcIdToken idToken = new OidcIdToken(ID_TOKEN_VALUE, Instant.ofEpochMilli(IAT_VALUE), Instant.ofEpochMilli(EXP_VALUE), CLAIMS); assertThat(idToken.getClaims()).isEqualTo(CLAIMS); assertThat(idToken.getTokenValue()).isEqualTo(ID_TOKEN_VALUE); assertThat(idToken.getIssuer().toString()).isEqualTo(ISS_VALUE); assertThat(idToken.getSubject()).isEqualTo(SUB_VALUE); assertThat(idToken.getAudience()).isEqualTo(AUD_VALUE); assertThat(idToken.getIssuedAt().toEpochMilli()).isEqualTo(IAT_VALUE); assertThat(idToken.getExpiresAt().toEpochMilli()).isEqualTo(EXP_VALUE); assertThat(idToken.getAuthenticatedAt().getEpochSecond()).isEqualTo(AUTH_TIME_VALUE); assertThat(idToken.getNonce()).isEqualTo(NONCE_VALUE); assertThat(idToken.getAuthenticationContextClass()).isEqualTo(ACR_VALUE); assertThat(idToken.getAuthenticationMethods()).isEqualTo(AMR_VALUE); assertThat(idToken.getAuthorizedParty()).isEqualTo(AZP_VALUE); assertThat(idToken.getAccessTokenHash()).isEqualTo(AT_HASH_VALUE); assertThat(idToken.getAuthorizationCodeHash()).isEqualTo(C_HASH_VALUE); } }
4,827
33.985507
107
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.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.oauth2.core.oidc; import java.time.Instant; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcUserInfo} */ public class OidcIdTokenBuilderTests { @Test public void buildWhenCalledTwiceThenGeneratesTwoOidcIdTokens() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token"); // @formatter:off OidcIdToken first = idTokenBuilder.tokenValue("V1") .claim("TEST_CLAIM_1", "C1") .build(); OidcIdToken second = idTokenBuilder.tokenValue("V2") .claim("TEST_CLAIM_1", "C2") .claim("TEST_CLAIM_2", "C3") .build(); // @formatter:on assertThat(first.getClaims()).hasSize(1); assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1"); assertThat(first.getTokenValue()).isEqualTo("V1"); assertThat(second.getClaims()).hasSize(2); assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2"); assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3"); assertThat(second.getTokenValue()).isEqualTo("V2"); } @Test public void expiresAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token"); Instant now = Instant.now(); OidcIdToken idToken = idTokenBuilder.expiresAt(now).build(); assertThat(idToken.getExpiresAt()).isSameAs(now); idToken = idTokenBuilder.expiresAt(now).build(); assertThat(idToken.getExpiresAt()).isSameAs(now); assertThatIllegalArgumentException() .isThrownBy(() -> idTokenBuilder.claim(IdTokenClaimNames.EXP, "not an instant").build()); } @Test public void issuedAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token"); Instant now = Instant.now(); OidcIdToken idToken = idTokenBuilder.issuedAt(now).build(); assertThat(idToken.getIssuedAt()).isSameAs(now); idToken = idTokenBuilder.issuedAt(now).build(); assertThat(idToken.getIssuedAt()).isSameAs(now); assertThatIllegalArgumentException() .isThrownBy(() -> idTokenBuilder.claim(IdTokenClaimNames.IAT, "not an instant").build()); } @Test public void subjectWhenUsingGenericOrNamedClaimMethodThenLastOneWins() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token"); String generic = new String("sub"); String named = new String("sub"); // @formatter:off OidcIdToken idToken = idTokenBuilder .subject(named) .claim(IdTokenClaimNames.SUB, generic) .build(); // @formatter:on assertThat(idToken.getSubject()).isSameAs(generic); idToken = idTokenBuilder.claim(IdTokenClaimNames.SUB, generic).subject(named).build(); assertThat(idToken.getSubject()).isSameAs(named); } @Test public void claimsWhenRemovingAClaimThenIsNotPresent() { // @formatter:off OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token") .claim("needs", "a claim"); OidcIdToken idToken = idTokenBuilder.subject("sub") .claims((claims) -> claims.remove(IdTokenClaimNames.SUB)) .build(); // @formatter:on assertThat(idToken.getSubject()).isNull(); } @Test public void claimsWhenAddingAClaimThenIsPresent() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token"); String name = new String("name"); String value = new String("value"); // @formatter:off OidcIdToken idToken = idTokenBuilder .claims((claims) -> claims.put(name, value)) .build(); // @formatter:on assertThat(idToken.getClaims()).hasSize(1); assertThat(idToken.getClaims().get(name)).isSameAs(value); } }
4,322
35.327731
93
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/TestOidcIdTokens.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.oauth2.core.oidc; import java.time.Instant; /** * Test {@link OidcIdToken}s * * @author Josh Cummings */ public final class TestOidcIdTokens { private TestOidcIdTokens() { } public static OidcIdToken.Builder idToken() { // @formatter:off return OidcIdToken.withTokenValue("id-token") .issuer("https://example.com") .subject("subject") .issuedAt(Instant.now()) .expiresAt(Instant.now() .plusSeconds(86400)) .claim("id", "id"); // @formatter:on } }
1,150
25.159091
75
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoBuilderTests.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.oauth2.core.oidc; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OidcUserInfo} */ public class OidcUserInfoBuilderTests { @Test public void buildWhenCalledTwiceThenGeneratesTwoOidcUserInfos() { OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder(); // @formatter:off OidcUserInfo first = userInfoBuilder .claim("TEST_CLAIM_1", "C1") .build(); OidcUserInfo second = userInfoBuilder .claim("TEST_CLAIM_1", "C2") .claim("TEST_CLAIM_2", "C3") .build(); // @formatter:on assertThat(first.getClaims()).hasSize(1); assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1"); assertThat(second.getClaims()).hasSize(2); assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2"); assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3"); } @Test public void subjectWhenUsingGenericOrNamedClaimMethodThenLastOneWins() { OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder(); String generic = new String("sub"); String named = new String("sub"); // @formatter:off OidcUserInfo userInfo = userInfoBuilder .subject(named) .claim(IdTokenClaimNames.SUB, generic) .build(); // @formatter:on assertThat(userInfo.getSubject()).isSameAs(generic); // @formatter:off userInfo = userInfoBuilder .claim(IdTokenClaimNames.SUB, generic) .subject(named) .build(); // @formatter:on assertThat(userInfo.getSubject()).isSameAs(named); } @Test public void claimsWhenRemovingAClaimThenIsNotPresent() { // @formatter:off OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder() .claim("needs", "a claim"); OidcUserInfo userInfo = userInfoBuilder.subject("sub") .claims((claims) -> claims.remove(IdTokenClaimNames.SUB)) .build(); // @formatter:on assertThat(userInfo.getSubject()).isNull(); } @Test public void claimsWhenAddingAClaimThenIsPresent() { OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder(); String name = new String("name"); String value = new String("value"); // @formatter:off OidcUserInfo userInfo = userInfoBuilder .claims((claims) -> claims.put(name, value)) .build(); // @formatter:on assertThat(userInfo.getClaims()).hasSize(1); assertThat(userInfo.getClaims().get(name)).isSameAs(value); } }
3,019
30.789474
75
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/TestOidcUsers.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.oauth2.core.oidc.user; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; /** * @author Joe Grandja */ public final class TestOidcUsers { private TestOidcUsers() { } public static DefaultOidcUser create() { OidcIdToken idToken = idToken(); OidcUserInfo userInfo = userInfo(); return new DefaultOidcUser(authorities(idToken, userInfo), idToken, userInfo); } private static OidcIdToken idToken() { Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(3600); // @formatter:off return OidcIdToken.withTokenValue("id-token") .issuedAt(issuedAt) .expiresAt(expiresAt) .subject("subject") .issuer("http://localhost/issuer") .audience(Collections.unmodifiableSet(new LinkedHashSet<>(Collections.singletonList("client")))) .authorizedParty("client") .build(); // @formatter:on } private static OidcUserInfo userInfo() { return OidcUserInfo.builder().subject("subject").name("full name").build(); } private static Collection<? extends GrantedAuthority> authorities(OidcIdToken idToken, OidcUserInfo userInfo) { return new LinkedHashSet<>(Arrays.asList(new OidcUserAuthority(idToken, userInfo), new SimpleGrantedAuthority("SCOPE_read"), new SimpleGrantedAuthority("SCOPE_write"))); } }
2,288
32.173913
112
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/DefaultOidcUserTests.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.oauth2.core.oidc.user; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultOidcUser}. * * @author Vedran Pavic * @author Joe Grandja */ public class DefaultOidcUserTests { private static final SimpleGrantedAuthority AUTHORITY = new SimpleGrantedAuthority("ROLE_USER"); private static final Set<GrantedAuthority> AUTHORITIES = Collections.singleton(AUTHORITY); private static final String SUBJECT = "test-subject"; private static final String EMAIL = "test-subject@example.com"; private static final String NAME = "test-name"; private static final Map<String, Object> ID_TOKEN_CLAIMS = new HashMap<>(); private static final Map<String, Object> USER_INFO_CLAIMS = new HashMap<>(); static { ID_TOKEN_CLAIMS.put(IdTokenClaimNames.ISS, "https://example.com"); ID_TOKEN_CLAIMS.put(IdTokenClaimNames.SUB, SUBJECT); USER_INFO_CLAIMS.put(StandardClaimNames.NAME, NAME); USER_INFO_CLAIMS.put(StandardClaimNames.EMAIL, EMAIL); } private static final OidcIdToken ID_TOKEN = new OidcIdToken("id-token-value", Instant.EPOCH, Instant.MAX, ID_TOKEN_CLAIMS); private static final OidcUserInfo USER_INFO = new OidcUserInfo(USER_INFO_CLAIMS); @Test public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultOidcUser(AUTHORITIES, null)); } @Test public void constructorWhenNameAttributeKeyInvalidThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultOidcUser(AUTHORITIES, ID_TOKEN, "invalid")); } @Test public void constructorWhenAuthoritiesIsNullThenCreatedWithEmptyAuthorities() { DefaultOidcUser user = new DefaultOidcUser(null, ID_TOKEN); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getName()).isEqualTo(SUBJECT); assertThat(user.getAuthorities()).isEmpty(); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); } @Test public void constructorWhenAuthoritiesIsEmptyThenCreated() { DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.NO_AUTHORITIES, ID_TOKEN); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getName()).isEqualTo(SUBJECT); assertThat(user.getAuthorities()).isEmpty(); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); } @Test public void constructorWhenAuthoritiesIdTokenProvidedThenCreated() { DefaultOidcUser user = new DefaultOidcUser(AUTHORITIES, ID_TOKEN); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getName()).isEqualTo(SUBJECT); assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); } @Test public void constructorWhenAuthoritiesIdTokenNameAttributeKeyProvidedThenCreated() { DefaultOidcUser user = new DefaultOidcUser(AUTHORITIES, ID_TOKEN, IdTokenClaimNames.SUB); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getName()).isEqualTo(SUBJECT); assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB); } @Test public void constructorWhenAuthoritiesIdTokenUserInfoProvidedThenCreated() { DefaultOidcUser user = new DefaultOidcUser(AUTHORITIES, ID_TOKEN, USER_INFO); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB, StandardClaimNames.NAME, StandardClaimNames.EMAIL); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getUserInfo()).isEqualTo(USER_INFO); assertThat(user.getName()).isEqualTo(SUBJECT); assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB, StandardClaimNames.NAME, StandardClaimNames.EMAIL); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { DefaultOidcUser user = new DefaultOidcUser(AUTHORITIES, ID_TOKEN, USER_INFO, StandardClaimNames.EMAIL); assertThat(user.getClaims()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB, StandardClaimNames.NAME, StandardClaimNames.EMAIL); assertThat(user.getIdToken()).isEqualTo(ID_TOKEN); assertThat(user.getUserInfo()).isEqualTo(USER_INFO); assertThat(user.getName()).isEqualTo(EMAIL); assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY); assertThat(user.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB, StandardClaimNames.NAME, StandardClaimNames.EMAIL); } }
6,690
43.311258
111
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthorityTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.oidc.user; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcUserAuthority}. * * @author Joe Grandja */ public class OidcUserAuthorityTests { private static final String AUTHORITY = "ROLE_USER"; private static final String SUBJECT = "test-subject"; private static final String EMAIL = "test-subject@example.com"; private static final String NAME = "test-name"; private static final Map<String, Object> ID_TOKEN_CLAIMS = new HashMap<>(); private static final Map<String, Object> USER_INFO_CLAIMS = new HashMap<>(); static { ID_TOKEN_CLAIMS.put(IdTokenClaimNames.ISS, "https://example.com"); ID_TOKEN_CLAIMS.put(IdTokenClaimNames.SUB, SUBJECT); USER_INFO_CLAIMS.put(StandardClaimNames.NAME, NAME); USER_INFO_CLAIMS.put(StandardClaimNames.EMAIL, EMAIL); } private static final OidcIdToken ID_TOKEN = new OidcIdToken("id-token-value", Instant.EPOCH, Instant.MAX, ID_TOKEN_CLAIMS); private static final OidcUserInfo USER_INFO = new OidcUserInfo(USER_INFO_CLAIMS); @Test public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OidcUserAuthority(null)); } @Test public void constructorWhenUserInfoIsNullThenDoesNotThrowAnyException() { new OidcUserAuthority(ID_TOKEN, null); } @Test public void constructorWhenAuthorityIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new OidcUserAuthority(null, ID_TOKEN, USER_INFO)); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OidcUserAuthority userAuthority = new OidcUserAuthority(AUTHORITY, ID_TOKEN, USER_INFO); assertThat(userAuthority.getIdToken()).isEqualTo(ID_TOKEN); assertThat(userAuthority.getUserInfo()).isEqualTo(USER_INFO); assertThat(userAuthority.getAuthority()).isEqualTo(AUTHORITY); assertThat(userAuthority.getAttributes()).containsOnlyKeys(IdTokenClaimNames.ISS, IdTokenClaimNames.SUB, StandardClaimNames.NAME, StandardClaimNames.EMAIL); } }
3,206
35.443182
106
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/DefaultMapOAuth2AccessTokenResponseConverterTests.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.oauth2.core.endpoint; import java.time.Duration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2RefreshToken; /** * Tests for {@link DefaultMapOAuth2AccessTokenResponseConverter}. * * @author Steve Riesenberg */ public class DefaultMapOAuth2AccessTokenResponseConverterTests { private Converter<Map<String, Object>, OAuth2AccessTokenResponse> messageConverter; @BeforeEach public void setup() { this.messageConverter = new DefaultMapOAuth2AccessTokenResponseConverter(); } @Test public void shouldConvertFull() { Map<String, Object> map = new HashMap<>(); map.put("access_token", "access-token-1234"); map.put("token_type", "bearer"); map.put("expires_in", "3600"); map.put("scope", "read write"); map.put("refresh_token", "refresh-token-1234"); map.put("custom_parameter_1", "custom-value-1"); map.put("custom_parameter_2", "custom-value-2"); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessToken accessToken = converted.getAccessToken(); Assertions.assertNotNull(accessToken); Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); Set<String> scopes = accessToken.getScopes(); Assertions.assertNotNull(scopes); Assertions.assertEquals(2, scopes.size()); Assertions.assertTrue(scopes.contains("read")); Assertions.assertTrue(scopes.contains("write")); Assertions.assertEquals(3600, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); OAuth2RefreshToken refreshToken = converted.getRefreshToken(); Assertions.assertNotNull(refreshToken); Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue()); Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Assertions.assertNotNull(additionalParameters); Assertions.assertEquals(2, additionalParameters.size()); Assertions.assertEquals("custom-value-1", additionalParameters.get("custom_parameter_1")); Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2")); } @Test public void shouldConvertMinimal() { Map<String, Object> map = new HashMap<>(); map.put("access_token", "access-token-1234"); map.put("token_type", "bearer"); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessToken accessToken = converted.getAccessToken(); Assertions.assertNotNull(accessToken); Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); Set<String> scopes = accessToken.getScopes(); Assertions.assertNotNull(scopes); Assertions.assertEquals(0, scopes.size()); Assertions.assertEquals(1, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); OAuth2RefreshToken refreshToken = converted.getRefreshToken(); Assertions.assertNull(refreshToken); Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Assertions.assertNotNull(additionalParameters); Assertions.assertEquals(0, additionalParameters.size()); } @Test public void shouldConvertWithUnsupportedExpiresIn() { Map<String, Object> map = new HashMap<>(); map.put("access_token", "access-token-1234"); map.put("token_type", "bearer"); map.put("expires_in", "2100-01-01-abc"); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessToken accessToken = converted.getAccessToken(); Assertions.assertNotNull(accessToken); Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); Set<String> scopes = accessToken.getScopes(); Assertions.assertNotNull(scopes); Assertions.assertEquals(0, scopes.size()); Assertions.assertEquals(1, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); OAuth2RefreshToken refreshToken = converted.getRefreshToken(); Assertions.assertNull(refreshToken); Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Assertions.assertNotNull(additionalParameters); Assertions.assertEquals(0, additionalParameters.size()); } // gh-9685 @Test public void shouldConvertWithNumericExpiresIn() { Map<String, Object> map = new HashMap<>(); map.put("access_token", "access-token-1234"); map.put("token_type", "bearer"); map.put("expires_in", 3600); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessToken accessToken = converted.getAccessToken(); Assertions.assertNotNull(accessToken); Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); Assertions.assertEquals(3600, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); } // gh-9685 @Test public void shouldConvertWithObjectAdditionalParameter() { Map<String, Object> map = new HashMap<>(); map.put("access_token", "access-token-1234"); map.put("token_type", "bearer"); map.put("expires_in", "3600"); map.put("scope", "read write"); map.put("refresh_token", "refresh-token-1234"); Map<String, Object> nestedObject = new LinkedHashMap<>(); nestedObject.put("a", "first value"); nestedObject.put("b", "second value"); map.put("custom_parameter_1", nestedObject); map.put("custom_parameter_2", "custom-value-2"); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessToken accessToken = converted.getAccessToken(); Assertions.assertNotNull(accessToken); Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); Set<String> scopes = accessToken.getScopes(); Assertions.assertNotNull(scopes); Assertions.assertEquals(2, scopes.size()); Assertions.assertTrue(scopes.contains("read")); Assertions.assertTrue(scopes.contains("write")); Assertions.assertEquals(3600, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); OAuth2RefreshToken refreshToken = converted.getRefreshToken(); Assertions.assertNotNull(refreshToken); Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue()); Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Assertions.assertNotNull(additionalParameters); Assertions.assertEquals(2, additionalParameters.size()); Assertions.assertEquals(nestedObject, additionalParameters.get("custom_parameter_1")); Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2")); } }
7,887
43.564972
92
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/TestOAuth2AuthorizationExchanges.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.oauth2.core.endpoint; /** * @author Rob Winch * @author Eddú Meléndez * @since 5.1 */ public final class TestOAuth2AuthorizationExchanges { private TestOAuth2AuthorizationExchanges() { } public static OAuth2AuthorizationExchange success() { OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().build(); OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build(); return new OAuth2AuthorizationExchange(request, response); } public static OAuth2AuthorizationExchange failure() { OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().build(); OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.error().build(); return new OAuth2AuthorizationExchange(request, response); } }
1,462
33.833333
92
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.endpoint; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizationResponse}. * * @author Joe Grandja */ public class OAuth2AuthorizationResponseTests { private static final String AUTH_CODE = "auth-code"; private static final String REDIRECT_URI = "https://example.com"; private static final String STATE = "state"; private static final String ERROR_CODE = "error-code"; private static final String ERROR_DESCRIPTION = "error-description"; private static final String ERROR_URI = "error-uri"; @Test public void buildSuccessResponseWhenAuthCodeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.success(null) .redirectUri(REDIRECT_URI) .state(STATE) .build() // @formatter:on ); } @Test public void buildSuccessResponseWhenRedirectUriIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.success(AUTH_CODE) .redirectUri(null) .state(STATE) .build() // @formatter:on ); } @Test public void buildSuccessResponseWhenStateIsNullThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationResponse.success(AUTH_CODE) .redirectUri(REDIRECT_URI) .state(null) .build(); // @formatter:on } @Test public void buildSuccessResponseWhenAllAttributesProvidedThenAllAttributesAreSet() { // @formatter:off OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success(AUTH_CODE) .redirectUri(REDIRECT_URI) .state(STATE) .build(); assertThat(authorizationResponse.getCode()) .isEqualTo(AUTH_CODE); assertThat(authorizationResponse.getRedirectUri()) .isEqualTo(REDIRECT_URI); assertThat(authorizationResponse.getState()) .isEqualTo(STATE); // @formatter:on } @Test public void buildSuccessResponseWhenErrorCodeIsSetThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.success(AUTH_CODE) .redirectUri(REDIRECT_URI) .state(STATE) .errorCode(ERROR_CODE) .build() // @formatter:on ); } @Test public void buildErrorResponseWhenErrorCodeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.error(null) .redirectUri(REDIRECT_URI) .state(STATE) .build() // @formatter:on ); } @Test public void buildErrorResponseWhenRedirectUriIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.error(ERROR_CODE) .redirectUri(null) .state(STATE) .build() // @formatter:on ); } @Test public void buildErrorResponseWhenStateIsNullThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationResponse.error(ERROR_CODE) .redirectUri(REDIRECT_URI) .state(null) .build(); // @formatter:on } @Test public void buildErrorResponseWhenAllAttributesProvidedThenAllAttributesAreSet() { // @formatter:off OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.error(ERROR_CODE) .errorDescription(ERROR_DESCRIPTION) .errorUri(ERROR_URI) .redirectUri(REDIRECT_URI) .state(STATE) .build(); assertThat(authorizationResponse.getError().getErrorCode()) .isEqualTo(ERROR_CODE); assertThat(authorizationResponse.getError().getDescription()) .isEqualTo(ERROR_DESCRIPTION); assertThat(authorizationResponse.getError().getUri()) .isEqualTo(ERROR_URI); assertThat(authorizationResponse.getRedirectUri()) .isEqualTo(REDIRECT_URI); assertThat(authorizationResponse.getState()) .isEqualTo(STATE); // @formatter:on } @Test public void buildErrorResponseWhenAuthCodeIsSetThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AuthorizationResponse.error(ERROR_CODE) .redirectUri(REDIRECT_URI) .state(STATE) .code(AUTH_CODE) .build() // @formatter:on ); } }
5,053
27.715909
100
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/TestOAuth2AuthorizationResponses.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.oauth2.core.endpoint; /** * @author Rob Winch * @since 5.1 */ public final class TestOAuth2AuthorizationResponses { private TestOAuth2AuthorizationResponses() { } public static OAuth2AuthorizationResponse.Builder success() { // @formatter:off return OAuth2AuthorizationResponse.success("authorization-code") .state("state") .redirectUri("https://example.com/authorize/oauth2/code/registration-id"); // @formatter:on } public static OAuth2AuthorizationResponse.Builder error() { // @formatter:off return OAuth2AuthorizationResponse.error("error") .redirectUri("https://example.com/authorize/oauth2/code/registration-id") .errorUri("https://example.com/error"); // @formatter:on } }
1,383
29.755556
78
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/TestOAuth2AuthorizationRequests.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.oauth2.core.endpoint; import java.util.HashMap; import java.util.Map; /** * @author Rob Winch * @since 5.1 */ public final class TestOAuth2AuthorizationRequests { private TestOAuth2AuthorizationRequests() { } public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> attributes = new HashMap<>(); attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); // @formatter:off return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId(clientId) .redirectUri("https://example.com/authorize/oauth2/code/registration-id") .state("state") .attributes(attributes); // @formatter:on } public static OAuth2AuthorizationRequest.Builder oidcRequest() { return request().scope("openid"); } }
1,567
29.745098
77
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchangeTests.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core.endpoint; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizationExchange}. * * @author Joe Grandja */ public class OAuth2AuthorizationExchangeTests { @Test public void constructorWhenAuthorizationRequestIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new OAuth2AuthorizationExchange(null, TestOAuth2AuthorizationResponses.success().build())); } @Test public void constructorWhenAuthorizationResponseIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(), null)); } @Test public void constructorWhenRequiredArgsProvidedThenCreated() { OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build(); OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse); assertThat(authorizationExchange.getAuthorizationRequest()).isEqualTo(authorizationRequest); assertThat(authorizationExchange.getAuthorizationResponse()).isEqualTo(authorizationResponse); } }
2,119
38.259259
107
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/DefaultOAuth2AccessTokenResponseMapConverterTests.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.oauth2.core.endpoint; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.oauth2.core.OAuth2AccessToken; /** * Tests for {@link DefaultOAuth2AccessTokenResponseMapConverter}. * * @author Steve Riesenberg */ public class DefaultOAuth2AccessTokenResponseMapConverterTests { private Converter<OAuth2AccessTokenResponse, Map<String, Object>> messageConverter; @BeforeEach public void setup() { this.messageConverter = new DefaultOAuth2AccessTokenResponseMapConverter(); } @Test public void shouldConvertFull() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("custom_parameter_1", "custom-value-1"); additionalParameters.put("custom_parameter_2", "custom-value-2"); Set<String> scopes = new HashSet<>(); scopes.add("read"); scopes.add("write"); // @formatter:off OAuth2AccessTokenResponse build = OAuth2AccessTokenResponse.withToken("access-token-value-1234") .expiresIn(3699) .additionalParameters(additionalParameters) .refreshToken("refresh-token-value-1234") .scopes(scopes) .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); // @formatter:on Map<String, Object> result = this.messageConverter.convert(build); Assertions.assertEquals(7, result.size()); Assertions.assertEquals("access-token-value-1234", result.get("access_token")); Assertions.assertEquals("refresh-token-value-1234", result.get("refresh_token")); Assertions.assertEquals("read write", result.get("scope")); Assertions.assertEquals("Bearer", result.get("token_type")); Assertions.assertNotNull(result.get("expires_in")); Assertions.assertEquals("custom-value-1", result.get("custom_parameter_1")); Assertions.assertEquals("custom-value-2", result.get("custom_parameter_2")); } @Test public void shouldConvertMinimal() { // @formatter:off OAuth2AccessTokenResponse build = OAuth2AccessTokenResponse.withToken("access-token-value-1234") .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); // @formatter:on Map<String, Object> result = this.messageConverter.convert(build); Assertions.assertEquals(3, result.size()); Assertions.assertEquals("access-token-value-1234", result.get("access_token")); Assertions.assertEquals("Bearer", result.get("token_type")); Assertions.assertNotNull(result.get("expires_in")); } // gh-9685 @Test public void shouldConvertWithObjectAdditionalParameter() { Map<String, Object> nestedObject = new LinkedHashMap<>(); nestedObject.put("a", "first value"); nestedObject.put("b", "second value"); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("custom_parameter_1", nestedObject); additionalParameters.put("custom_parameter_2", "custom-value-2"); Set<String> scopes = new HashSet<>(); scopes.add("read"); scopes.add("write"); // @formatter:off OAuth2AccessTokenResponse build = OAuth2AccessTokenResponse.withToken("access-token-value-1234") .expiresIn(3699) .additionalParameters(additionalParameters) .refreshToken("refresh-token-value-1234") .scopes(scopes) .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); // @formatter:on Map<String, Object> result = this.messageConverter.convert(build); Assertions.assertEquals(7, result.size()); Assertions.assertEquals("access-token-value-1234", result.get("access_token")); Assertions.assertEquals("refresh-token-value-1234", result.get("refresh_token")); Assertions.assertEquals("read write", result.get("scope")); Assertions.assertEquals("Bearer", result.get("token_type")); Assertions.assertNotNull(result.get("expires_in")); Assertions.assertEquals(nestedObject, result.get("custom_parameter_1")); Assertions.assertEquals("custom-value-2", result.get("custom_parameter_2")); } }
4,740
38.181818
98
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/TestOAuth2AccessTokenResponses.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.oauth2.core.endpoint; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; /** * @author Rob Winch * @since 5.1 */ public final class TestOAuth2AccessTokenResponses { private TestOAuth2AccessTokenResponses() { } public static OAuth2AccessTokenResponse.Builder accessTokenResponse() { // @formatter:off return OAuth2AccessTokenResponse .withToken("token") .tokenType(OAuth2AccessToken.TokenType.BEARER); // @formatter:on } public static OAuth2AccessTokenResponse.Builder oidcAccessTokenResponse() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token"); return accessTokenResponse().scopes(Collections.singleton(OidcScopes.OPENID)) .additionalParameters(additionalParameters); } }
1,691
31.538462
81
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponseTests.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.oauth2.core.endpoint; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AccessTokenResponse}. * * @author Luander Ribeiro * @author Joe Grandja */ public class OAuth2AccessTokenResponseTests { private static final String TOKEN_VALUE = "access-token"; private static final String REFRESH_TOKEN_VALUE = "refresh-token"; private static final long EXPIRES_IN = Instant.now().plusSeconds(5).toEpochMilli(); @Test public void buildWhenTokenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AccessTokenResponse.withToken(null) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(EXPIRES_IN) .build() // @formatter:on ); } @Test public void buildWhenTokenTypeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(null) .expiresIn(EXPIRES_IN) .build() // @formatter:on ); } @Test public void buildWhenExpiresInIsZeroThenExpiresAtOneSecondAfterIssueAt() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(0) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getIssuedAt().plusSeconds(1)); } @Test public void buildWhenExpiresInIsNegativeThenExpiresAtOneSecondAfterIssueAt() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(-1L) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getIssuedAt().plusSeconds(1)); } @Test public void buildWhenAllAttributesProvidedThenAllAttributesAreSet() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .refreshToken(REFRESH_TOKEN_VALUE) .additionalParameters(additionalParameters) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken()).isNotNull(); assertThat(tokenResponse.getAccessToken().getTokenValue()).isEqualTo(TOKEN_VALUE); assertThat(tokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(tokenResponse.getAccessToken().getIssuedAt()).isNotNull(); assertThat(tokenResponse.getAccessToken().getExpiresAt()).isAfterOrEqualTo(expiresAt); assertThat(tokenResponse.getAccessToken().getScopes()).isEqualTo(scopes); assertThat(tokenResponse.getRefreshToken().getTokenValue()).isEqualTo(REFRESH_TOKEN_VALUE); assertThat(tokenResponse.getAdditionalParameters()).isEqualTo(additionalParameters); } @Test public void buildWhenResponseThenAllAttributesAreSet() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .refreshToken(REFRESH_TOKEN_VALUE) .additionalParameters(additionalParameters) .build(); // @formatter:on OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse).build(); assertThat(withResponse.getAccessToken().getTokenValue()) .isEqualTo(tokenResponse.getAccessToken().getTokenValue()); assertThat(withResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(withResponse.getAccessToken().getIssuedAt()).isEqualTo(tokenResponse.getAccessToken().getIssuedAt()); assertThat(withResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getExpiresAt()); assertThat(withResponse.getAccessToken().getScopes()).isEqualTo(tokenResponse.getAccessToken().getScopes()); assertThat(withResponse.getRefreshToken().getTokenValue()) .isEqualTo(tokenResponse.getRefreshToken().getTokenValue()); assertThat(withResponse.getAdditionalParameters()).isEqualTo(tokenResponse.getAdditionalParameters()); } @Test public void buildWhenResponseAndRefreshNullThenRefreshNull() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .additionalParameters(additionalParameters) .build(); // @formatter:on OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse).build(); assertThat(withResponse.getRefreshToken()).isNull(); } @Test public void buildWhenResponseAndExpiresInThenExpiresAtEqualToIssuedAtPlusExpiresIn() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); // @formatter:on long expiresIn = 30; OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .expiresIn(expiresIn).build(); assertThat(withResponse.getAccessToken().getExpiresAt()) .isEqualTo(withResponse.getAccessToken().getIssuedAt().plusSeconds(expiresIn)); } }
7,394
39.190217
114
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequestTests.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.oauth2.core.endpoint; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.AuthorizationGrantType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizationRequest}. * * @author Luander Ribeiro * @author Joe Grandja */ public class OAuth2AuthorizationRequestTests { private static final String AUTHORIZATION_URI = "https://provider.com/oauth2/authorize"; private static final String CLIENT_ID = "client-id"; private static final String REDIRECT_URI = "https://example.com"; private static final Set<String> SCOPES = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); private static final String STATE = "state"; @Test public void buildWhenAuthorizationUriIsNullThenThrowIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> OAuth2AuthorizationRequest .authorizationCode() .authorizationUri(null) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .build() ); // @formatter:on } @Test public void buildWhenClientIdIsNullThenThrowIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(null) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .build() ); // @formatter:on } @Test public void buildWhenRedirectUriIsNullForAuthorizationCodeThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(null) .scopes(SCOPES) .state(STATE) .build(); // @formatter:on } @Test public void buildWhenScopesIsNullThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(null) .state(STATE) .build(); // @formatter:on } @Test public void buildWhenStateIsNullThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(null) .build(); // @formatter:on } @Test public void buildWhenAdditionalParametersEmptyThenDoesNotThrowAnyException() { // @formatter:off OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .additionalParameters(Map::clear) .build(); // @formatter:on } @Test public void buildWhenAuthorizationCodeThenGrantTypeResponseTypeIsSet() { // @formatter:off OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(null) .scopes(SCOPES) .state(STATE) .build(); // @formatter:on assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE); } @Test public void buildWhenAllValuesProvidedThenAllValuesAreSet() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); Map<String, Object> attributes = new HashMap<>(); attributes.put("attribute1", "value1"); attributes.put("attribute2", "value2"); // @formatter:off OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .additionalParameters(additionalParameters) .attributes(attributes) .authorizationRequestUri(AUTHORIZATION_URI) .build(); // @formatter:on assertThat(authorizationRequest.getAuthorizationUri()).isEqualTo(AUTHORIZATION_URI); assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE); assertThat(authorizationRequest.getClientId()).isEqualTo(CLIENT_ID); assertThat(authorizationRequest.getRedirectUri()).isEqualTo(REDIRECT_URI); assertThat(authorizationRequest.getScopes()).isEqualTo(SCOPES); assertThat(authorizationRequest.getState()).isEqualTo(STATE); assertThat(authorizationRequest.getAdditionalParameters()).isEqualTo(additionalParameters); assertThat(authorizationRequest.getAttributes()).isEqualTo(attributes); assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo(AUTHORIZATION_URI); } @Test public void buildWhenAuthorizationRequestUriSetThenOverridesDefault() { // @formatter:off OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .authorizationRequestUri(AUTHORIZATION_URI) .build(); // @formatter:on assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo(AUTHORIZATION_URI); } @Test public void buildWhenAuthorizationRequestUriFunctionSetThenOverridesDefault() { // @formatter:off OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .authorizationRequestUri((uriBuilder) -> URI.create(AUTHORIZATION_URI)) .build(); // @formatter:on assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo(AUTHORIZATION_URI); } @Test public void buildWhenAuthorizationRequestUriNotSetThenDefaultSet() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES) .state(STATE).additionalParameters(additionalParameters).build(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isNotNull(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo("https://provider.com/oauth2/authorize?" + "response_type=code&client_id=client-id&" + "scope=scope1%20scope2&state=state&" + "redirect_uri=https://example.com&param1=value1&param2=value2"); } @Test public void buildWhenRequiredParametersSetThenAuthorizationRequestUriIncludesRequiredParametersOnly() { OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID).build(); assertThat(authorizationRequest.getAuthorizationRequestUri()) .isEqualTo("https://provider.com/oauth2/authorize?response_type=code&client_id=client-id"); } @Test public void fromWhenAuthorizationRequestIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizationRequest.from(null)); } @Test public void fromWhenAuthorizationRequestProvidedThenValuesAreCopied() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); Map<String, Object> attributes = new HashMap<>(); attributes.put("attribute1", "value1"); attributes.put("attribute2", "value2"); // @formatter:off OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(AUTHORIZATION_URI) .clientId(CLIENT_ID) .redirectUri(REDIRECT_URI) .scopes(SCOPES) .state(STATE) .additionalParameters(additionalParameters) .attributes(attributes) .build(); OAuth2AuthorizationRequest authorizationRequestCopy = OAuth2AuthorizationRequest.from(authorizationRequest) .build(); // @formatter:on assertThat(authorizationRequestCopy.getAuthorizationUri()) .isEqualTo(authorizationRequest.getAuthorizationUri()); assertThat(authorizationRequestCopy.getGrantType()).isEqualTo(authorizationRequest.getGrantType()); assertThat(authorizationRequestCopy.getResponseType()).isEqualTo(authorizationRequest.getResponseType()); assertThat(authorizationRequestCopy.getClientId()).isEqualTo(authorizationRequest.getClientId()); assertThat(authorizationRequestCopy.getRedirectUri()).isEqualTo(authorizationRequest.getRedirectUri()); assertThat(authorizationRequestCopy.getScopes()).isEqualTo(authorizationRequest.getScopes()); assertThat(authorizationRequestCopy.getState()).isEqualTo(authorizationRequest.getState()); assertThat(authorizationRequestCopy.getAdditionalParameters()) .isEqualTo(authorizationRequest.getAdditionalParameters()); assertThat(authorizationRequestCopy.getAttributes()).isEqualTo(authorizationRequest.getAttributes()); assertThat(authorizationRequestCopy.getAuthorizationRequestUri()) .isEqualTo(authorizationRequest.getAuthorizationRequestUri()); } @Test public void buildWhenAuthorizationUriIncludesQueryParameterThenAuthorizationRequestUrlIncludesIt() { OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() .authorizationUri(AUTHORIZATION_URI + "?param1=value1&param2=value2").build(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isNotNull(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo("https://provider.com/oauth2/authorize?" + "param1=value1&param2=value2&" + "response_type=code&client_id=client-id&state=state&" + "redirect_uri=https://example.com/authorize/oauth2/code/registration-id"); } @Test public void buildWhenAuthorizationUriIncludesEscapedQueryParameterThenAuthorizationRequestUrlIncludesIt() { OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() .authorizationUri(AUTHORIZATION_URI + "?claims=%7B%22userinfo%22%3A%7B%22email_verified%22%3A%7B%22essential%22%3Atrue%7D%7D%7D") .build(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isNotNull(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo("https://provider.com/oauth2/authorize?" + "claims=%7B%22userinfo%22%3A%7B%22email_verified%22%3A%7B%22essential%22%3Atrue%7D%7D%7D&" + "response_type=code&client_id=client-id&state=state&" + "redirect_uri=https://example.com/authorize/oauth2/code/registration-id"); } @Test public void buildWhenNonAsciiAdditionalParametersThenProperlyEncoded() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("item amount", "19.95" + '\u20ac'); additionalParameters.put("item name", "H" + '\u00c5' + "M" + '\u00d6'); additionalParameters.put('\u00e2' + "ge", "4" + '\u00bd'); OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() .additionalParameters(additionalParameters).build(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isNotNull(); assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo( "https://example.com/login/oauth/authorize?" + "response_type=code&client_id=client-id&state=state&" + "redirect_uri=https://example.com/authorize/oauth2/code/registration-id&" + "item%20amount=19.95%E2%82%AC&%C3%A2ge=4%C2%BD&item%20name=H%C3%85M%C3%96"); } }
12,797
39.757962
114
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTypeTests.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.oauth2.core.endpoint; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OAuth2AuthorizationResponseType}. * * @author Joe Grandja */ public class OAuth2AuthorizationResponseTypeTests { @Test public void getValueWhenResponseTypeCodeThenReturnCode() { assertThat(OAuth2AuthorizationResponseType.CODE.getValue()).isEqualTo("code"); } }
1,073
28.833333
80
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.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.oauth2.core.http.converter; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OAuth2AccessTokenResponseHttpMessageConverter}. * * @author Joe Grandja */ public class OAuth2AccessTokenResponseHttpMessageConverterTests { private OAuth2AccessTokenResponseHttpMessageConverter messageConverter; @BeforeEach public void setup() { this.messageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); } @Test public void supportsWhenOAuth2AccessTokenResponseThenTrue() { assertThat(this.messageConverter.supports(OAuth2AccessTokenResponse.class)).isTrue(); } @Test public void setAccessTokenResponseConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.messageConverter.setAccessTokenResponseConverter(null)); } @Test public void setAccessTokenResponseParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.messageConverter.setAccessTokenResponseParametersConverter(null)); } @Test public void readInternalWhenSuccessfulTokenResponseThenReadOAuth2AccessTokenResponse() throws Exception { // @formatter:off String tokenResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\",\n" + " \"scope\": \"read write\",\n" + " \"refresh_token\": \"refresh-token-1234\",\n" + " \"custom_parameter_1\": \"custom-value-1\",\n" + " \"custom_parameter_2\": \"custom-value-2\"\n" + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK); OAuth2AccessTokenResponse accessTokenResponse = this.messageConverter .readInternal(OAuth2AccessTokenResponse.class, response); assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234"); assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()) .isBeforeOrEqualTo(Instant.now().plusSeconds(3600)); assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write"); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234"); assertThat(accessTokenResponse.getAdditionalParameters()).containsExactly( entry("custom_parameter_1", "custom-value-1"), entry("custom_parameter_2", "custom-value-2")); } // gh-6463 @Test public void readInternalWhenSuccessfulTokenResponseWithObjectThenReadOAuth2AccessTokenResponse() { // @formatter:off String tokenResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 3600,\n" + " \"scope\": \"read write\",\n" + " \"refresh_token\": \"refresh-token-1234\",\n" + " \"custom_object_1\": {\"name1\": \"value1\"},\n" + " \"custom_object_2\": [\"value1\", \"value2\"],\n" + " \"custom_parameter_1\": \"custom-value-1\",\n" + " \"custom_parameter_2\": \"custom-value-2\"\n" + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK); OAuth2AccessTokenResponse accessTokenResponse = this.messageConverter .readInternal(OAuth2AccessTokenResponse.class, response); assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234"); assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()) .isBeforeOrEqualTo(Instant.now().plusSeconds(3600)); assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write"); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234"); Map<String, String> additionalParameters = accessTokenResponse.getAdditionalParameters().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> String.valueOf(entry.getValue()))); assertThat(additionalParameters).containsExactly(entry("custom_object_1", "{name1=value1}"), entry("custom_object_2", "[value1, value2]"), entry("custom_parameter_1", "custom-value-1"), entry("custom_parameter_2", "custom-value-2")); } // gh-8108 @Test public void readInternalWhenSuccessfulTokenResponseWithNullValueThenReadOAuth2AccessTokenResponse() { // @formatter:off String tokenResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 3600,\n" + " \"scope\": null,\n" + " \"refresh_token\": \"refresh-token-1234\"\n" + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK); OAuth2AccessTokenResponse accessTokenResponse = this.messageConverter .readInternal(OAuth2AccessTokenResponse.class, response); assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234"); assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()) .isBeforeOrEqualTo(Instant.now().plusSeconds(3600)); assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty(); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234"); } @Test public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() { Converter tokenResponseConverter = mock(Converter.class); given(tokenResponseConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setAccessTokenResponseConverter(tokenResponseConverter); String tokenResponse = "{}"; MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK); assertThatExceptionOfType(HttpMessageNotReadableException.class) .isThrownBy(() -> this.messageConverter.readInternal(OAuth2AccessTokenResponse.class, response)) .withMessageContaining("An error occurred reading the OAuth 2.0 Access Token Response"); } @Test public void writeInternalWhenOAuth2AccessTokenResponseThenWriteTokenResponse() throws Exception { Instant expiresAt = Instant.now().plusSeconds(3600); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("read", "write")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("custom_parameter_1", "custom-value-1"); additionalParameters.put("custom_parameter_2", "custom-value-2"); // @formatter:off OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234") .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .refreshToken("refresh-token-1234") .additionalParameters(additionalParameters) .build(); // @formatter:on MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.messageConverter.writeInternal(accessTokenResponse, outputMessage); String tokenResponse = outputMessage.getBodyAsString(); assertThat(tokenResponse).contains("\"access_token\":\"access-token-1234\""); assertThat(tokenResponse).contains("\"token_type\":\"Bearer\""); assertThat(tokenResponse).contains("\"expires_in\""); assertThat(tokenResponse).contains("\"scope\":\"read write\""); assertThat(tokenResponse).contains("\"refresh_token\":\"refresh-token-1234\""); assertThat(tokenResponse).contains("\"custom_parameter_1\":\"custom-value-1\""); assertThat(tokenResponse).contains("\"custom_parameter_2\":\"custom-value-2\""); } @Test public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() { Converter tokenResponseParametersConverter = mock(Converter.class); given(tokenResponseParametersConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setAccessTokenResponseParametersConverter(tokenResponseParametersConverter); // @formatter:off OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse .withToken("access-token-1234") .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(Instant.now().plusSeconds(3600) .toEpochMilli()) .build(); // @formatter:on MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); assertThatExceptionOfType(HttpMessageNotWritableException.class) .isThrownBy(() -> this.messageConverter.writeInternal(accessTokenResponse, outputMessage)) .withMessageContaining("An error occurred writing the OAuth 2.0 Access Token Response"); } }
10,644
47.607306
112
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2DeviceAuthorizationResponseHttpMessageConverterTests.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.oauth2.core.http.converter; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2DeviceAuthorizationResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OAuth2DeviceAuthorizationResponseHttpMessageConverter}. * * @author Steve Riesenberg */ public class OAuth2DeviceAuthorizationResponseHttpMessageConverterTests { private OAuth2DeviceAuthorizationResponseHttpMessageConverter messageConverter; @BeforeEach public void setup() { this.messageConverter = new OAuth2DeviceAuthorizationResponseHttpMessageConverter(); } @Test public void supportsWhenOAuth2DeviceAuthorizationResponseThenTrue() { assertThat(this.messageConverter.supports(OAuth2DeviceAuthorizationResponse.class)).isTrue(); } @Test public void setDeviceAuthorizationResponseConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.messageConverter.setDeviceAuthorizationResponseConverter(null)); } @Test public void setDeviceAuthorizationResponseParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.messageConverter.setDeviceAuthorizationResponseParametersConverter(null)); } @Test public void readInternalWhenSuccessfulResponseWithAllParametersThenReadOAuth2DeviceAuthorizationResponse() { // @formatter:off String authorizationResponse = """ { "device_code": "GmRhm_DnyEy", "user_code": "WDJB-MJHT", "verification_uri": "https://example.com/device", "verification_uri_complete": "https://example.com/device?user_code=WDJB-MJHT", "expires_in": 1800, "interval": 5, "custom_parameter_1": "custom-value-1", "custom_parameter_2": "custom-value-2" } """; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(authorizationResponse.getBytes(), HttpStatus.OK); OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = this.messageConverter .readInternal(OAuth2DeviceAuthorizationResponse.class, response); assertThat(deviceAuthorizationResponse.getDeviceCode().getTokenValue()) .isEqualTo("GmRhm_DnyEy"); assertThat(deviceAuthorizationResponse.getDeviceCode().getIssuedAt()).isNotNull(); assertThat(deviceAuthorizationResponse.getDeviceCode().getExpiresAt()) .isBeforeOrEqualTo(Instant.now().plusSeconds(1800)); assertThat(deviceAuthorizationResponse.getUserCode().getTokenValue()).isEqualTo("WDJB-MJHT"); assertThat(deviceAuthorizationResponse.getUserCode().getIssuedAt()) .isEqualTo(deviceAuthorizationResponse.getDeviceCode().getIssuedAt()); assertThat(deviceAuthorizationResponse.getUserCode().getExpiresAt()) .isEqualTo(deviceAuthorizationResponse.getDeviceCode().getExpiresAt()); assertThat(deviceAuthorizationResponse.getVerificationUri()).isEqualTo("https://example.com/device"); assertThat(deviceAuthorizationResponse.getVerificationUriComplete()) .isEqualTo("https://example.com/device?user_code=WDJB-MJHT"); assertThat(deviceAuthorizationResponse.getInterval()).isEqualTo(5); assertThat(deviceAuthorizationResponse.getAdditionalParameters()).containsExactly( entry("custom_parameter_1", "custom-value-1"), entry("custom_parameter_2", "custom-value-2")); } @Test public void readInternalWhenSuccessfulResponseWithNullValuesThenReadOAuth2DeviceAuthorizationResponse() { // @formatter:off String authorizationResponse = """ { "device_code": "GmRhm_DnyEy", "user_code": "WDJB-MJHT", "verification_uri": "https://example.com/device", "verification_uri_complete": null, "expires_in": 1800, "interval": null } """; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(authorizationResponse.getBytes(), HttpStatus.OK); OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = this.messageConverter .readInternal(OAuth2DeviceAuthorizationResponse.class, response); assertThat(deviceAuthorizationResponse.getDeviceCode().getTokenValue()) .isEqualTo("GmRhm_DnyEy"); assertThat(deviceAuthorizationResponse.getDeviceCode().getIssuedAt()).isNotNull(); assertThat(deviceAuthorizationResponse.getDeviceCode().getExpiresAt()) .isBeforeOrEqualTo(Instant.now().plusSeconds(1800)); assertThat(deviceAuthorizationResponse.getUserCode().getTokenValue()).isEqualTo("WDJB-MJHT"); assertThat(deviceAuthorizationResponse.getUserCode().getIssuedAt()) .isEqualTo(deviceAuthorizationResponse.getDeviceCode().getIssuedAt()); assertThat(deviceAuthorizationResponse.getUserCode().getExpiresAt()) .isEqualTo(deviceAuthorizationResponse.getDeviceCode().getExpiresAt()); assertThat(deviceAuthorizationResponse.getVerificationUri()).isEqualTo("https://example.com/device"); assertThat(deviceAuthorizationResponse.getVerificationUriComplete()).isNull(); assertThat(deviceAuthorizationResponse.getInterval()).isEqualTo(0); } @Test @SuppressWarnings("unchecked") public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() { Converter<Map<String, Object>, OAuth2DeviceAuthorizationResponse> deviceAuthorizationResponseConverter = mock( Converter.class); given(deviceAuthorizationResponseConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setDeviceAuthorizationResponseConverter(deviceAuthorizationResponseConverter); String authorizationResponse = "{}"; MockClientHttpResponse response = new MockClientHttpResponse(authorizationResponse.getBytes(), HttpStatus.OK); assertThatExceptionOfType(HttpMessageNotReadableException.class) .isThrownBy(() -> this.messageConverter.readInternal(OAuth2DeviceAuthorizationResponse.class, response)) .withMessageContaining("An error occurred reading the OAuth 2.0 Device Authorization Response"); } @Test public void writeInternalWhenOAuth2DeviceAuthorizationResponseThenWriteResponse() { Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("custom_parameter_1", "custom-value-1"); additionalParameters.put("custom_parameter_2", "custom-value-2"); // @formatter:off OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = OAuth2DeviceAuthorizationResponse.with("GmRhm_DnyEy", "WDJB-MJHT") .verificationUri("https://example.com/device") .verificationUriComplete("https://example.com/device?user_code=WDJB-MJHT") .expiresIn(1800) .interval(5) .additionalParameters(additionalParameters) .build(); // @formatter:on MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.messageConverter.writeInternal(deviceAuthorizationResponse, outputMessage); String authorizationResponse = outputMessage.getBodyAsString(); assertThat(authorizationResponse).contains("\"device_code\":\"GmRhm_DnyEy\""); assertThat(authorizationResponse).contains("\"user_code\":\"WDJB-MJHT\""); assertThat(authorizationResponse).contains("\"verification_uri\":\"https://example.com/device\""); assertThat(authorizationResponse) .contains("\"verification_uri_complete\":\"https://example.com/device?user_code=WDJB-MJHT\""); assertThat(authorizationResponse).contains("\"expires_in\":1800"); assertThat(authorizationResponse).contains("\"interval\":5"); assertThat(authorizationResponse).contains("\"custom_parameter_1\":\"custom-value-1\""); assertThat(authorizationResponse).contains("\"custom_parameter_2\":\"custom-value-2\""); } @Test @SuppressWarnings("unchecked") public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() { Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> deviceAuthorizationResponseParametersConverter = mock( Converter.class); given(deviceAuthorizationResponseParametersConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter .setDeviceAuthorizationResponseParametersConverter(deviceAuthorizationResponseParametersConverter); // @formatter:off OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = OAuth2DeviceAuthorizationResponse.with("GmRhm_DnyEy", "WDJB-MJHT") .verificationUri("https://example.com/device") .expiresIn(1800) .build(); // @formatter:on MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); assertThatExceptionOfType(HttpMessageNotWritableException.class) .isThrownBy(() -> this.messageConverter.writeInternal(deviceAuthorizationResponse, outputMessage)) .withMessageContaining("An error occurred writing the OAuth 2.0 Device Authorization Response"); } }
10,159
48.082126
122
java
null
spring-security-main/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.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.oauth2.core.http.converter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.oauth2.core.OAuth2Error; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OAuth2ErrorHttpMessageConverter}. * * @author Joe Grandja */ public class OAuth2ErrorHttpMessageConverterTests { private OAuth2ErrorHttpMessageConverter messageConverter; @BeforeEach public void setup() { this.messageConverter = new OAuth2ErrorHttpMessageConverter(); } @Test public void supportsWhenOAuth2ErrorThenTrue() { assertThat(this.messageConverter.supports(OAuth2Error.class)).isTrue(); } @Test public void setErrorConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setErrorConverter(null)); } @Test public void setErrorParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setErrorParametersConverter(null)); } @Test public void readInternalWhenErrorResponseThenReadOAuth2Error() throws Exception { // @formatter:off String errorResponse = "{\n" + " \"error\": \"unauthorized_client\",\n" + " \"error_description\": \"The client is not authorized\",\n" + " \"error_uri\": \"https://tools.ietf.org/html/rfc6749#section-5.2\"\n" + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); OAuth2Error oauth2Error = this.messageConverter.readInternal(OAuth2Error.class, response); assertThat(oauth2Error.getErrorCode()).isEqualTo("unauthorized_client"); assertThat(oauth2Error.getDescription()).isEqualTo("The client is not authorized"); assertThat(oauth2Error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6749#section-5.2"); } // gh-8157 @Test public void readInternalWhenErrorResponseWithObjectThenReadOAuth2Error() throws Exception { // @formatter:off String errorResponse = "{\n" + " \"error\": \"unauthorized_client\",\n" + " \"error_description\": \"The client is not authorized\",\n" + " \"error_codes\": [65001],\n" + " \"error_uri\": \"https://tools.ietf.org/html/rfc6749#section-5.2\"\n" + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); OAuth2Error oauth2Error = this.messageConverter.readInternal(OAuth2Error.class, response); assertThat(oauth2Error.getErrorCode()).isEqualTo("unauthorized_client"); assertThat(oauth2Error.getDescription()).isEqualTo("The client is not authorized"); assertThat(oauth2Error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6749#section-5.2"); } @Test public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() { Converter errorConverter = mock(Converter.class); given(errorConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setErrorConverter(errorConverter); String errorResponse = "{}"; MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); assertThatExceptionOfType(HttpMessageNotReadableException.class) .isThrownBy(() -> this.messageConverter.readInternal(OAuth2Error.class, response)) .withMessageContaining("An error occurred reading the OAuth 2.0 Error"); } @Test public void writeInternalWhenOAuth2ErrorThenWriteErrorResponse() throws Exception { OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", "https://tools.ietf.org/html/rfc6749#section-5.2"); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.messageConverter.writeInternal(oauth2Error, outputMessage); String errorResponse = outputMessage.getBodyAsString(); assertThat(errorResponse).contains("\"error\":\"unauthorized_client\""); assertThat(errorResponse).contains("\"error_description\":\"The client is not authorized\""); assertThat(errorResponse).contains("\"error_uri\":\"https://tools.ietf.org/html/rfc6749#section-5.2\""); } @Test public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() { Converter errorParametersConverter = mock(Converter.class); given(errorParametersConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setErrorParametersConverter(errorParametersConverter); OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", "https://tools.ietf.org/html/rfc6749#section-5.2"); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); assertThatExceptionOfType(HttpMessageNotWritableException.class) .isThrownBy(() -> this.messageConverter.writeInternal(oauth2Error, outputMessage)) .withMessageContaining("An error occurred writing the OAuth 2.0 Error"); } }
6,322
44.818841
113
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/package-info.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Core classes and interfaces providing support for the OAuth 2.0 Authorization * Framework. */ package org.springframework.security.oauth2.core;
776
34.318182
80
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AuthorizationException.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.oauth2.core; import org.springframework.util.Assert; /** * Base exception for OAuth 2.0 Authorization errors. * * @author Joe Grandja * @since 5.1 */ public class OAuth2AuthorizationException extends RuntimeException { private final OAuth2Error error; /** * Constructs an {@code OAuth2AuthorizationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} */ public OAuth2AuthorizationException(OAuth2Error error) { this(error, error.toString()); } /** * Constructs an {@code OAuth2AuthorizationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the exception message * @since 5.3 */ public OAuth2AuthorizationException(OAuth2Error error, String message) { super(message); Assert.notNull(error, "error must not be null"); this.error = error; } /** * Constructs an {@code OAuth2AuthorizationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param cause the root cause */ public OAuth2AuthorizationException(OAuth2Error error, Throwable cause) { this(error, error.toString(), cause); } /** * Constructs an {@code OAuth2AuthorizationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the exception message * @param cause the root cause * @since 5.3 */ public OAuth2AuthorizationException(OAuth2Error error, String message, Throwable cause) { super(message, cause); Assert.notNull(error, "error must not be null"); this.error = error; } /** * Returns the {@link OAuth2Error OAuth 2.0 Error}. * @return the {@link OAuth2Error} */ public OAuth2Error getError() { return this.error; } }
2,445
28.829268
90
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AbstractOAuth2Token.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.oauth2.core; import java.io.Serializable; import java.time.Instant; import org.springframework.lang.Nullable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * Base class for OAuth 2.0 Token implementations. * * @author Joe Grandja * @since 5.0 * @see OAuth2Token * @see OAuth2AccessToken * @see OAuth2RefreshToken */ public abstract class AbstractOAuth2Token implements OAuth2Token, Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String tokenValue; private final Instant issuedAt; private final Instant expiresAt; /** * Sub-class constructor. * @param tokenValue the token value */ protected AbstractOAuth2Token(String tokenValue) { this(tokenValue, null, null); } /** * Sub-class constructor. * @param tokenValue the token value * @param issuedAt the time at which the token was issued, may be {@code null} * @param expiresAt the expiration time on or after which the token MUST NOT be * accepted, may be {@code null} */ protected AbstractOAuth2Token(String tokenValue, @Nullable Instant issuedAt, @Nullable Instant expiresAt) { Assert.hasText(tokenValue, "tokenValue cannot be empty"); if (issuedAt != null && expiresAt != null) { Assert.isTrue(expiresAt.isAfter(issuedAt), "expiresAt must be after issuedAt"); } this.tokenValue = tokenValue; this.issuedAt = issuedAt; this.expiresAt = expiresAt; } /** * Returns the token value. * @return the token value */ public String getTokenValue() { return this.tokenValue; } /** * Returns the time at which the token was issued. * @return the time the token was issued or {@code null} */ @Nullable public Instant getIssuedAt() { return this.issuedAt; } /** * Returns the expiration time on or after which the token MUST NOT be accepted. * @return the token expiration time or {@code null} */ @Nullable public Instant getExpiresAt() { return this.expiresAt; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AbstractOAuth2Token other = (AbstractOAuth2Token) obj; if (!this.getTokenValue().equals(other.getTokenValue())) { return false; } if ((this.getIssuedAt() != null) ? !this.getIssuedAt().equals(other.getIssuedAt()) : other.getIssuedAt() != null) { return false; } return (this.getExpiresAt() != null) ? this.getExpiresAt().equals(other.getExpiresAt()) : other.getExpiresAt() == null; } @Override public int hashCode() { int result = this.getTokenValue().hashCode(); result = 31 * result + ((this.getIssuedAt() != null) ? this.getIssuedAt().hashCode() : 0); result = 31 * result + ((this.getExpiresAt() != null) ? this.getExpiresAt().hashCode() : 0); return result; } }
3,577
27.624
108
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2TokenValidatorResult.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.oauth2.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.springframework.util.Assert; /** * A result emitted from an {@link OAuth2TokenValidator} validation attempt * * @author Josh Cummings * @since 5.1 */ public final class OAuth2TokenValidatorResult { static final OAuth2TokenValidatorResult NO_ERRORS = new OAuth2TokenValidatorResult(Collections.emptyList()); private final Collection<OAuth2Error> errors; private OAuth2TokenValidatorResult(Collection<OAuth2Error> errors) { Assert.notNull(errors, "errors cannot be null"); this.errors = new ArrayList<>(errors); } /** * Say whether this result indicates success * @return whether this result has errors */ public boolean hasErrors() { return !this.errors.isEmpty(); } /** * Return error details regarding the validation attempt * @return the collection of results in this result, if any; returns an empty list * otherwise */ public Collection<OAuth2Error> getErrors() { return this.errors; } /** * Construct a successful {@link OAuth2TokenValidatorResult} * @return an {@link OAuth2TokenValidatorResult} with no errors */ public static OAuth2TokenValidatorResult success() { return NO_ERRORS; } /** * Construct a failure {@link OAuth2TokenValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link OAuth2TokenValidatorResult} with the errors specified */ public static OAuth2TokenValidatorResult failure(OAuth2Error... errors) { return failure(Arrays.asList(errors)); } /** * Construct a failure {@link OAuth2TokenValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link OAuth2TokenValidatorResult} with the errors specified */ public static OAuth2TokenValidatorResult failure(Collection<OAuth2Error> errors) { return (errors.isEmpty()) ? NO_ERRORS : new OAuth2TokenValidatorResult(errors); } }
2,653
29.505747
109
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2TokenIntrospectionClaimNames.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.oauth2.core; /** * The names of the &quot;Introspection Claims&quot; defined by an * <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2.2">Introspection * Response</a>. * * @author Josh Cummings * @since 5.6 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2.2">OAuth * 2.0 Token Introspection (RFC7662)</a> * @see <a target="_blank" href= * "https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#token-introspection-response">OAuth * Parameters (IANA)</a> */ public final class OAuth2TokenIntrospectionClaimNames { /** * {@code active} - Indicator whether or not the token is currently active */ public static final String ACTIVE = "active"; /** * {@code username} - A human-readable identifier for the resource owner that * authorized the token */ public static final String USERNAME = "username"; /** * {@code client_id} - The Client identifier for the token */ public static final String CLIENT_ID = "client_id"; /** * {@code scope} - The scopes for the token */ public static final String SCOPE = "scope"; /** * {@code token_type} - The type of the token, for example {@code bearer}. */ public static final String TOKEN_TYPE = "token_type"; /** * {@code exp} - A timestamp indicating when the token expires */ public static final String EXP = "exp"; /** * {@code iat} - A timestamp indicating when the token was issued */ public static final String IAT = "iat"; /** * {@code nbf} - A timestamp indicating when the token is not to be used before */ public static final String NBF = "nbf"; /** * {@code sub} - Usually a machine-readable identifier of the resource owner who * authorized the token */ public static final String SUB = "sub"; /** * {@code aud} - The intended audience for the token */ public static final String AUD = "aud"; /** * {@code iss} - The issuer of the token */ public static final String ISS = "iss"; /** * {@code jti} - The identifier for the token */ public static final String JTI = "jti"; private OAuth2TokenIntrospectionClaimNames() { } }
2,803
27.04
112
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.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.oauth2.core; import java.util.Collection; import java.util.Map; import org.springframework.lang.Nullable; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.core.GrantedAuthority; /** * An {@link AuthenticatedPrincipal} that represents the principal associated with an * OAuth 2.0 token. * * @author Josh Cummings * @since 5.2 */ public interface OAuth2AuthenticatedPrincipal extends AuthenticatedPrincipal { /** * Get the OAuth 2.0 token attribute by name * @param name the name of the attribute * @param <A> the type of the attribute * @return the attribute or {@code null} otherwise */ @Nullable @SuppressWarnings("unchecked") default <A> A getAttribute(String name) { return (A) getAttributes().get(name); } /** * Get the OAuth 2.0 token attributes * @return the OAuth 2.0 token attributes */ Map<String, Object> getAttributes(); /** * Get the {@link Collection} of {@link GrantedAuthority}s associated with this OAuth * 2.0 token * @return the OAuth 2.0 token authorities */ Collection<? extends GrantedAuthority> getAuthorities(); }
1,797
28.47541
86
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/ClientAuthenticationMethod.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.oauth2.core; import java.io.Serializable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * The authentication method used when authenticating the client with the authorization * server. * * @author Joe Grandja * @since 5.0 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-2.3">Section * 2.3 Client Authentication</a> */ public final class ClientAuthenticationMethod implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; /** * @since 5.5 */ public static final ClientAuthenticationMethod CLIENT_SECRET_BASIC = new ClientAuthenticationMethod( "client_secret_basic"); /** * @since 5.5 */ public static final ClientAuthenticationMethod CLIENT_SECRET_POST = new ClientAuthenticationMethod( "client_secret_post"); /** * @since 5.5 */ public static final ClientAuthenticationMethod CLIENT_SECRET_JWT = new ClientAuthenticationMethod( "client_secret_jwt"); /** * @since 5.5 */ public static final ClientAuthenticationMethod PRIVATE_KEY_JWT = new ClientAuthenticationMethod("private_key_jwt"); /** * @since 5.2 */ public static final ClientAuthenticationMethod NONE = new ClientAuthenticationMethod("none"); private final String value; /** * Constructs a {@code ClientAuthenticationMethod} using the provided value. * @param value the value of the client authentication method */ public ClientAuthenticationMethod(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the client authentication method. * @return the value of the client authentication method */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } ClientAuthenticationMethod that = (ClientAuthenticationMethod) obj; return getValue().equals(that.getValue()); } @Override public int hashCode() { return getValue().hashCode(); } @Override public String toString() { return this.value; } }
2,885
25.971963
116
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AuthorizationGrantType.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.oauth2.core; import java.io.Serializable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * An authorization grant is a credential representing the resource owner's authorization * (to access it's protected resources) to the client and used by the client to obtain an * access token. * * <p> * The OAuth 2.0 Authorization Framework defines four standard grant types: authorization * code, resource owner password credentials, and client credentials. It also provides an * extensibility mechanism for defining additional grant types. * * @author Joe Grandja * @author Steve Riesenberg * @since 5.0 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section * 1.3 Authorization Grant</a> */ public final class AuthorizationGrantType implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; public static final AuthorizationGrantType AUTHORIZATION_CODE = new AuthorizationGrantType("authorization_code"); public static final AuthorizationGrantType REFRESH_TOKEN = new AuthorizationGrantType("refresh_token"); public static final AuthorizationGrantType CLIENT_CREDENTIALS = new AuthorizationGrantType("client_credentials"); /** * @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use * of the Resource Owner Password Credentials grant. See reference * <a target="_blank" href= * "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth * 2.0 Security Best Current Practice.</a> */ @Deprecated public static final AuthorizationGrantType PASSWORD = new AuthorizationGrantType("password"); /** * @since 5.5 */ public static final AuthorizationGrantType JWT_BEARER = new AuthorizationGrantType( "urn:ietf:params:oauth:grant-type:jwt-bearer"); /** * @since 6.1 */ public static final AuthorizationGrantType DEVICE_CODE = new AuthorizationGrantType( "urn:ietf:params:oauth:grant-type:device_code"); private final String value; /** * Constructs an {@code AuthorizationGrantType} using the provided value. * @param value the value of the authorization grant type */ public AuthorizationGrantType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the authorization grant type. * @return the value of the authorization grant type */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AuthorizationGrantType that = (AuthorizationGrantType) obj; return this.getValue().equals(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } }
3,563
31.697248
114
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AuthenticationMethod.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.oauth2.core; import java.io.Serializable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * The authentication method used when sending bearer access tokens in resource requests * to resource servers. * * @author MyeongHyeon Lee * @since 5.1 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6750#section-2">Section 2 * Authenticated Requests</a> */ public final class AuthenticationMethod implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; public static final AuthenticationMethod HEADER = new AuthenticationMethod("header"); public static final AuthenticationMethod FORM = new AuthenticationMethod("form"); public static final AuthenticationMethod QUERY = new AuthenticationMethod("query"); private final String value; /** * Constructs an {@code AuthenticationMethod} using the provided value. * @param value the value of the authentication method type */ public AuthenticationMethod(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the authentication method type. * @return the value of the authentication method type */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AuthenticationMethod that = (AuthenticationMethod) obj; return this.getValue().equals(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } }
2,346
28.3375
91
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AccessToken.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.oauth2.core; import java.io.Serializable; import java.time.Instant; import java.util.Collections; import java.util.Set; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * An implementation of an {@link AbstractOAuth2Token} representing an OAuth 2.0 Access * Token. * * <p> * An access token is a credential that represents an authorization granted by the * resource owner to the client. It is primarily used by the client to access protected * resources on either a resource server or the authorization server that originally * issued the access token. * * @author Joe Grandja * @since 5.0 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.4">Section * 1.4 Access Token</a> */ public class OAuth2AccessToken extends AbstractOAuth2Token { private final TokenType tokenType; private final Set<String> scopes; /** * Constructs an {@code OAuth2AccessToken} using the provided parameters. * @param tokenType the token type * @param tokenValue the token value * @param issuedAt the time at which the token was issued * @param expiresAt the expiration time on or after which the token MUST NOT be * accepted */ public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt) { this(tokenType, tokenValue, issuedAt, expiresAt, Collections.emptySet()); } /** * Constructs an {@code OAuth2AccessToken} using the provided parameters. * @param tokenType the token type * @param tokenValue the token value * @param issuedAt the time at which the token was issued * @param expiresAt the expiration time on or after which the token MUST NOT be * accepted * @param scopes the scope(s) associated to the token */ public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt, Set<String> scopes) { super(tokenValue, issuedAt, expiresAt); Assert.notNull(tokenType, "tokenType cannot be null"); this.tokenType = tokenType; this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet()); } /** * Returns the {@link TokenType token type}. * @return the {@link TokenType} */ public TokenType getTokenType() { return this.tokenType; } /** * Returns the scope(s) associated to the token. * @return the scope(s) associated to the token */ public Set<String> getScopes() { return this.scopes; } /** * Access Token Types. * * @see <a target="_blank" href= * "https://tools.ietf.org/html/rfc6749#section-7.1">Section 7.1 Access Token * Types</a> */ public static final class TokenType implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; public static final TokenType BEARER = new TokenType("Bearer"); private final String value; private TokenType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the token type. * @return the value of the token type */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } TokenType that = (TokenType) obj; return this.getValue().equalsIgnoreCase(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } } }
4,178
28.638298
104
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2RefreshToken.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.oauth2.core; import java.time.Instant; /** * An implementation of an {@link AbstractOAuth2Token} representing an OAuth 2.0 Refresh * Token. * * <p> * A refresh token is a credential that represents an authorization granted by the * resource owner to the client. It is used by the client to obtain a new access token * when the current access token becomes invalid or expires, or to obtain additional * access tokens with identical or narrower scope. * * @author Joe Grandja * @since 5.1 * @see OAuth2AccessToken * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.5">Section * 1.5 Refresh Token</a> */ public class OAuth2RefreshToken extends AbstractOAuth2Token { /** * Constructs an {@code OAuth2RefreshToken} using the provided parameters. * @param tokenValue the token value * @param issuedAt the time at which the token was issued */ public OAuth2RefreshToken(String tokenValue, Instant issuedAt) { this(tokenValue, issuedAt, null); } /** * Constructs an {@code OAuth2RefreshToken} using the provided parameters. * @param tokenValue the token value * @param issuedAt the time at which the token was issued * @param expiresAt the time at which the token expires * @since 5.5 */ public OAuth2RefreshToken(String tokenValue, Instant issuedAt, Instant expiresAt) { super(tokenValue, issuedAt, expiresAt); } }
2,045
33.1
89
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AuthenticationException.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.oauth2.core; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.util.Assert; /** * This exception is thrown for all OAuth 2.0 related {@link Authentication} errors. * * <p> * There are a number of scenarios where an error may occur, for example: * <ul> * <li>The authorization request or token request is missing a required parameter</li> * <li>Missing or invalid client identifier</li> * <li>Invalid or mismatching redirection URI</li> * <li>The requested scope is invalid, unknown, or malformed</li> * <li>The resource owner or authorization server denied the access request</li> * <li>Client authentication failed</li> * <li>The provided authorization grant (authorization code, resource owner credentials) * is invalid, expired, or revoked</li> * </ul> * * @author Joe Grandja * @since 5.0 */ public class OAuth2AuthenticationException extends AuthenticationException { private final OAuth2Error error; /** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * @param errorCode the {@link OAuth2ErrorCodes OAuth 2.0 Error Code} * @since 5.5 */ public OAuth2AuthenticationException(String errorCode) { this(new OAuth2Error(errorCode)); } /** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} */ public OAuth2AuthenticationException(OAuth2Error error) { this(error, error.getDescription()); } /** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param cause the root cause */ public OAuth2AuthenticationException(OAuth2Error error, Throwable cause) { this(error, cause.getMessage(), cause); } /** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message */ public OAuth2AuthenticationException(OAuth2Error error, String message) { this(error, message, null); } /** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message * @param cause the root cause */ public OAuth2AuthenticationException(OAuth2Error error, String message, Throwable cause) { super(message, cause); Assert.notNull(error, "error cannot be null"); this.error = error; } /** * Returns the {@link OAuth2Error OAuth 2.0 Error}. * @return the {@link OAuth2Error} */ public OAuth2Error getError() { return this.error; } }
3,410
32.441176
91
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2DeviceCode.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.oauth2.core; import java.time.Instant; /** * An implementation of an {@link AbstractOAuth2Token} representing a device code as part * of the OAuth 2.0 Device Authorization Grant. * * @author Steve Riesenberg * @since 6.1 * @see OAuth2UserCode * @see <a target="_blank" href= "https://tools.ietf.org/html/rfc8628#section-3.2">Section * 3.2 Device Authorization Response</a> */ public class OAuth2DeviceCode extends AbstractOAuth2Token { /** * Constructs an {@code OAuth2DeviceCode} using the provided parameters. * @param tokenValue the token value * @param issuedAt the time at which the token was issued * @param expiresAt the time at which the token expires */ public OAuth2DeviceCode(String tokenValue, Instant issuedAt, Instant expiresAt) { super(tokenValue, issuedAt, expiresAt); } }
1,477
32.590909
90
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2TokenValidator.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.oauth2.core; /** * Implementations of this interface are responsible for &quot;verifying&quot; the * validity and/or constraints of the attributes contained in an OAuth 2.0 Token. * * @author Joe Grandja * @author Josh Cummings * @since 5.1 */ @FunctionalInterface public interface OAuth2TokenValidator<T extends OAuth2Token> { /** * Verify the validity and/or constraints of the provided OAuth 2.0 Token. * @param token an OAuth 2.0 token * @return OAuth2TokenValidationResult the success or failure detail of the validation */ OAuth2TokenValidatorResult validate(T token); }
1,257
32.105263
87
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Error.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.core; import java.io.Serializable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * A representation of an OAuth 2.0 Error. * * <p> * At a minimum, an error response will contain an error code. The error code may be one * of the standard codes defined by the specification, or a new code defined in the OAuth * Extensions Error Registry, for cases where protocol extensions require additional error * code(s) above the standard codes. * * @author Joe Grandja * @since 5.0 * @see OAuth2ErrorCodes * @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-11.4">Section * 11.4 OAuth Extensions Error Registry</a> */ public class OAuth2Error implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String errorCode; private final String description; private final String uri; /** * Constructs an {@code OAuth2Error} using the provided parameters. * @param errorCode the error code */ public OAuth2Error(String errorCode) { this(errorCode, null, null); } /** * Constructs an {@code OAuth2Error} using the provided parameters. * @param errorCode the error code * @param description the error description * @param uri the error uri */ public OAuth2Error(String errorCode, String description, String uri) { Assert.hasText(errorCode, "errorCode cannot be empty"); this.errorCode = errorCode; this.description = description; this.uri = uri; } /** * Returns the error code. * @return the error code */ public final String getErrorCode() { return this.errorCode; } /** * Returns the error description. * @return the error description */ public final String getDescription() { return this.description; } /** * Returns the error uri. * @return the error uri */ public final String getUri() { return this.uri; } @Override public String toString() { return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } }
2,772
26.73
107
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2UserCode.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.oauth2.core; import java.time.Instant; /** * An implementation of an {@link AbstractOAuth2Token} representing a user code as part of * the OAuth 2.0 Device Authorization Grant. * * @author Steve Riesenberg * @since 6.1 * @see OAuth2DeviceCode * @see <a target="_blank" href= "https://tools.ietf.org/html/rfc8628#section-3.2">Section * 3.2 Device Authorization Response</a> */ public class OAuth2UserCode extends AbstractOAuth2Token { /** * Constructs an {@code OAuth2UserCode} using the provided parameters. * @param tokenValue the token value * @param issuedAt the time at which the token was issued * @param expiresAt the time at which the token expires */ public OAuth2UserCode(String tokenValue, Instant issuedAt, Instant expiresAt) { super(tokenValue, issuedAt, expiresAt); } }
1,471
32.454545
90
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.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.oauth2.core; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.util.Assert; /** * A domain object that wraps the attributes of an OAuth 2.0 token. * * @author Clement Ng * @author Josh Cummings * @since 5.2 */ public final class DefaultOAuth2AuthenticatedPrincipal implements OAuth2AuthenticatedPrincipal, Serializable { private final Map<String, Object> attributes; private final Collection<GrantedAuthority> authorities; private final String name; /** * Constructs an {@code DefaultOAuth2AuthenticatedPrincipal} using the provided * parameters. * @param attributes the attributes of the OAuth 2.0 token * @param authorities the authorities of the OAuth 2.0 token */ public DefaultOAuth2AuthenticatedPrincipal(Map<String, Object> attributes, Collection<GrantedAuthority> authorities) { this(null, attributes, authorities); } /** * Constructs an {@code DefaultOAuth2AuthenticatedPrincipal} using the provided * parameters. * @param name the name attached to the OAuth 2.0 token * @param attributes the attributes of the OAuth 2.0 token * @param authorities the authorities of the OAuth 2.0 token */ public DefaultOAuth2AuthenticatedPrincipal(String name, Map<String, Object> attributes, Collection<GrantedAuthority> authorities) { Assert.notEmpty(attributes, "attributes cannot be empty"); this.attributes = Collections.unmodifiableMap(attributes); this.authorities = (authorities != null) ? Collections.unmodifiableCollection(authorities) : AuthorityUtils.NO_AUTHORITIES; this.name = (name != null) ? name : (String) this.attributes.get("sub"); } /** * Gets the attributes of the OAuth 2.0 token in map form. * @return a {@link Map} of the attribute's objects keyed by the attribute's names */ @Override public Map<String, Object> getAttributes() { return this.attributes; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public String getName() { return this.name; } }
2,900
31.233333
110
java
null
spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Token.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.oauth2.core; import java.time.Instant; import org.springframework.lang.Nullable; /** * Core interface representing an OAuth 2.0 Token. * * @author Joe Grandja * @since 5.5 * @see AbstractOAuth2Token */ public interface OAuth2Token { /** * Returns the token value. * @return the token value */ String getTokenValue(); /** * Returns the time at which the token was issued. * @return the time the token was issued or {@code null} */ @Nullable default Instant getIssuedAt() { return null; } /** * Returns the expiration time on or after which the token MUST NOT be accepted. * @return the token expiration time or {@code null} */ @Nullable default Instant getExpiresAt() { return null; } }
1,391
23.421053
81
java