Polish spring-security-openid main code

Manually polish `spring-security-openid` following the formatting
and checkstyle fixes.

Issue gh-8945
This commit is contained in:
Phillip Webb 2020-07-31 22:33:29 -07:00 committed by Rob Winch
parent ba19a9e4b6
commit 5924ed885b
5 changed files with 38 additions and 89 deletions

View File

@ -80,27 +80,28 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
@Override @Override
public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm) public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm)
throws OpenIDConsumerException { throws OpenIDConsumerException {
List<DiscoveryInformation> discoveries; List<DiscoveryInformation> discoveries = getDiscoveries(identityUrl);
DiscoveryInformation information = this.consumerManager.associate(discoveries);
req.getSession().setAttribute(DISCOVERY_INFO_KEY, information);
AuthRequest authReq = getAuthRequest(req, identityUrl, returnToUrl, realm, information);
return authReq.getDestinationUrl(true);
}
private List<DiscoveryInformation> getDiscoveries(String identityUrl) throws OpenIDConsumerException {
try { try {
discoveries = this.consumerManager.discover(identityUrl); return this.consumerManager.discover(identityUrl);
} }
catch (DiscoveryException ex) { catch (DiscoveryException ex) {
throw new OpenIDConsumerException("Error during discovery", ex); throw new OpenIDConsumerException("Error during discovery", ex);
} }
}
DiscoveryInformation information = this.consumerManager.associate(discoveries); private AuthRequest getAuthRequest(HttpServletRequest req, String identityUrl, String returnToUrl, String realm,
req.getSession().setAttribute(DISCOVERY_INFO_KEY, information); DiscoveryInformation information) throws OpenIDConsumerException {
AuthRequest authReq;
try { try {
authReq = this.consumerManager.authenticate(information, returnToUrl, realm); AuthRequest authReq = this.consumerManager.authenticate(information, returnToUrl, realm);
this.logger.debug("Looking up attribute fetch list for identifier: " + identityUrl); this.logger.debug("Looking up attribute fetch list for identifier: " + identityUrl);
List<OpenIDAttribute> attributesToFetch = this.attributesToFetchFactory.createAttributeList(identityUrl); List<OpenIDAttribute> attributesToFetch = this.attributesToFetchFactory.createAttributeList(identityUrl);
if (!attributesToFetch.isEmpty()) { if (!attributesToFetch.isEmpty()) {
req.getSession().setAttribute(ATTRIBUTE_LIST_KEY, attributesToFetch); req.getSession().setAttribute(ATTRIBUTE_LIST_KEY, attributesToFetch);
FetchRequest fetchRequest = FetchRequest.createFetchRequest(); FetchRequest fetchRequest = FetchRequest.createFetchRequest();
@ -112,12 +113,11 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
} }
authReq.addExtension(fetchRequest); authReq.addExtension(fetchRequest);
} }
return authReq;
} }
catch (MessageException | ConsumerException ex) { catch (MessageException | ConsumerException ex) {
throw new OpenIDConsumerException("Error processing ConsumerManager authentication", ex); throw new OpenIDConsumerException("Error processing ConsumerManager authentication", ex);
} }
return authReq.getDestinationUrl(true);
} }
@Override @Override
@ -125,42 +125,32 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
// extract the parameters from the authentication response // extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider) // (which comes in as a HTTP request from the OpenID provider)
ParameterList openidResp = new ParameterList(request.getParameterMap()); ParameterList openidResp = new ParameterList(request.getParameterMap());
// retrieve the previously stored discovery information // retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(DISCOVERY_INFO_KEY); DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(DISCOVERY_INFO_KEY);
if (discovered == null) { if (discovered == null) {
throw new OpenIDConsumerException( throw new OpenIDConsumerException(
"DiscoveryInformation is not available. Possible causes are lost session or replay attack"); "DiscoveryInformation is not available. Possible causes are lost session or replay attack");
} }
List<OpenIDAttribute> attributesToFetch = (List<OpenIDAttribute>) request.getSession() List<OpenIDAttribute> attributesToFetch = (List<OpenIDAttribute>) request.getSession()
.getAttribute(ATTRIBUTE_LIST_KEY); .getAttribute(ATTRIBUTE_LIST_KEY);
request.getSession().removeAttribute(DISCOVERY_INFO_KEY); request.getSession().removeAttribute(DISCOVERY_INFO_KEY);
request.getSession().removeAttribute(ATTRIBUTE_LIST_KEY); request.getSession().removeAttribute(ATTRIBUTE_LIST_KEY);
// extract the receiving URL from the HTTP request // extract the receiving URL from the HTTP request
StringBuffer receivingURL = request.getRequestURL(); StringBuffer receivingURL = request.getRequestURL();
String queryString = request.getQueryString(); String queryString = request.getQueryString();
if (StringUtils.hasLength(queryString)) { if (StringUtils.hasLength(queryString)) {
receivingURL.append("?").append(request.getQueryString()); receivingURL.append("?").append(request.getQueryString());
} }
// verify the response // verify the response
VerificationResult verification; VerificationResult verification;
try { try {
verification = this.consumerManager.verify(receivingURL.toString(), openidResp, discovered); verification = this.consumerManager.verify(receivingURL.toString(), openidResp, discovered);
} }
catch (MessageException | AssociationException | DiscoveryException ex) { catch (MessageException | AssociationException | DiscoveryException ex) {
throw new OpenIDConsumerException("Error verifying openid response", ex); throw new OpenIDConsumerException("Error verifying openid response", ex);
} }
// examine the verification result and extract the verified identifier // examine the verification result and extract the verified identifier
Identifier verified = verification.getVerifiedId(); Identifier verified = verification.getVerifiedId();
if (verified == null) { if (verified == null) {
Identifier id = discovered.getClaimedIdentifier(); Identifier id = discovered.getClaimedIdentifier();
return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE,
@ -168,30 +158,23 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
"Verification status message: [" + verification.getStatusMsg() + "]", "Verification status message: [" + verification.getStatusMsg() + "]",
Collections.<OpenIDAttribute>emptyList()); Collections.<OpenIDAttribute>emptyList());
} }
List<OpenIDAttribute> attributes = fetchAxAttributes(verification.getAuthResponse(), attributesToFetch); List<OpenIDAttribute> attributes = fetchAxAttributes(verification.getAuthResponse(), attributesToFetch);
return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, verified.getIdentifier(), return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, verified.getIdentifier(),
"some message", attributes); "some message", attributes);
} }
List<OpenIDAttribute> fetchAxAttributes(Message authSuccess, List<OpenIDAttribute> attributesToFetch) List<OpenIDAttribute> fetchAxAttributes(Message authSuccess, List<OpenIDAttribute> attributesToFetch)
throws OpenIDConsumerException { throws OpenIDConsumerException {
if (attributesToFetch == null || !authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { if (attributesToFetch == null || !authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
return Collections.emptyList(); return Collections.emptyList();
} }
this.logger.debug("Extracting attributes retrieved by attribute exchange"); this.logger.debug("Extracting attributes retrieved by attribute exchange");
List<OpenIDAttribute> attributes = Collections.emptyList(); List<OpenIDAttribute> attributes = Collections.emptyList();
try { try {
MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX); MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX);
if (ext instanceof FetchResponse) { if (ext instanceof FetchResponse) {
FetchResponse fetchResp = (FetchResponse) ext; FetchResponse fetchResp = (FetchResponse) ext;
attributes = new ArrayList<>(attributesToFetch.size()); attributes = new ArrayList<>(attributesToFetch.size());
for (OpenIDAttribute attr : attributesToFetch) { for (OpenIDAttribute attr : attributesToFetch) {
List<String> values = fetchResp.getAttributeValues(attr.getName()); List<String> values = fetchResp.getAttributeValues(attr.getName());
if (!values.isEmpty()) { if (!values.isEmpty()) {
@ -205,11 +188,9 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
catch (MessageException ex) { catch (MessageException ex) {
throw new OpenIDConsumerException("Attribute retrieval failed", ex); throw new OpenIDConsumerException("Attribute retrieval failed", ex);
} }
if (this.logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
this.logger.debug("Retrieved attributes" + attributes); this.logger.debug("Retrieved attributes" + attributes);
} }
return attributes; return attributes;
} }

View File

@ -95,7 +95,6 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
super.afterPropertiesSet(); super.afterPropertiesSet();
if (this.consumer == null) { if (this.consumer == null) {
try { try {
this.consumer = new OpenID4JavaConsumer(); this.consumer = new OpenID4JavaConsumer();
@ -104,7 +103,6 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
throw new IllegalArgumentException("Failed to initialize OpenID", ex); throw new IllegalArgumentException("Failed to initialize OpenID", ex);
} }
} }
if (this.returnToUrlParameters.isEmpty() && getRememberMeServices() instanceof AbstractRememberMeServices) { if (this.returnToUrlParameters.isEmpty() && getRememberMeServices() instanceof AbstractRememberMeServices) {
this.returnToUrlParameters = new HashSet<>(); this.returnToUrlParameters = new HashSet<>();
this.returnToUrlParameters.add(((AbstractRememberMeServices) getRememberMeServices()).getParameter()); this.returnToUrlParameters.add(((AbstractRememberMeServices) getRememberMeServices()).getParameter());
@ -124,12 +122,9 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException { throws AuthenticationException, IOException {
OpenIDAuthenticationToken token; OpenIDAuthenticationToken token;
String identity = request.getParameter("openid.identity"); String identity = request.getParameter("openid.identity");
if (!StringUtils.hasText(identity)) { if (!StringUtils.hasText(identity)) {
String claimedIdentity = obtainUsername(request); String claimedIdentity = obtainUsername(request);
try { try {
String returnToUrl = buildReturnToUrl(request); String returnToUrl = buildReturnToUrl(request);
String realm = lookupRealm(returnToUrl); String realm = lookupRealm(returnToUrl);
@ -139,7 +134,6 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
this.logger.debug("Redirecting to " + openIdUrl); this.logger.debug("Redirecting to " + openIdUrl);
} }
response.sendRedirect(openIdUrl); response.sendRedirect(openIdUrl);
// Indicate to parent class that authentication is continuing. // Indicate to parent class that authentication is continuing.
return null; return null;
} }
@ -149,34 +143,27 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
"Unable to process claimed identity '" + claimedIdentity + "'"); "Unable to process claimed identity '" + claimedIdentity + "'");
} }
} }
if (this.logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
this.logger.debug("Supplied OpenID identity is " + identity); this.logger.debug("Supplied OpenID identity is " + identity);
} }
try { try {
token = this.consumer.endConsumption(request); token = this.consumer.endConsumption(request);
} }
catch (OpenIDConsumerException oice) { catch (OpenIDConsumerException ex) {
throw new AuthenticationServiceException("Consumer error", oice); throw new AuthenticationServiceException("Consumer error", ex);
} }
token.setDetails(this.authenticationDetailsSource.buildDetails(request)); token.setDetails(this.authenticationDetailsSource.buildDetails(request));
// delegate to the authentication provider // delegate to the authentication provider
Authentication authentication = this.getAuthenticationManager().authenticate(token); Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication; return authentication;
} }
protected String lookupRealm(String returnToUrl) { protected String lookupRealm(String returnToUrl) {
String mapping = this.realmMapping.get(returnToUrl); String mapping = this.realmMapping.get(returnToUrl);
if (mapping == null) { if (mapping == null) {
try { try {
URL url = new URL(returnToUrl); URL url = new URL(returnToUrl);
int port = url.getPort(); int port = url.getPort();
StringBuilder realmBuffer = new StringBuilder(returnToUrl.length()).append(url.getProtocol()) StringBuilder realmBuffer = new StringBuilder(returnToUrl.length()).append(url.getProtocol())
.append("://").append(url.getHost()); .append("://").append(url.getHost());
if (port > 0) { if (port > 0) {
@ -189,7 +176,6 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
this.logger.warn("returnToUrl was not a valid URL: [" + returnToUrl + "]", ex); this.logger.warn("returnToUrl was not a valid URL: [" + returnToUrl + "]", ex);
} }
} }
return mapping; return mapping;
} }
@ -201,25 +187,20 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
*/ */
protected String buildReturnToUrl(HttpServletRequest request) { protected String buildReturnToUrl(HttpServletRequest request) {
StringBuffer sb = request.getRequestURL(); StringBuffer sb = request.getRequestURL();
Iterator<String> iterator = this.returnToUrlParameters.iterator(); Iterator<String> iterator = this.returnToUrlParameters.iterator();
boolean isFirst = true; boolean isFirst = true;
while (iterator.hasNext()) { while (iterator.hasNext()) {
String name = iterator.next(); String name = iterator.next();
// Assume for simplicity that there is only one value // Assume for simplicity that there is only one value
String value = request.getParameter(name); String value = request.getParameter(name);
if (value == null) { if (value == null) {
continue; continue;
} }
if (isFirst) { if (isFirst) {
sb.append("?"); sb.append("?");
isFirst = false; isFirst = false;
} }
sb.append(utf8UrlEncode(name)).append("=").append(utf8UrlEncode(value)); sb.append(utf8UrlEncode(name)).append("=").append(utf8UrlEncode(value));
if (iterator.hasNext()) { if (iterator.hasNext()) {
sb.append("&"); sb.append("&");
} }
@ -232,12 +213,10 @@ public class OpenIDAuthenticationFilter extends AbstractAuthenticationProcessing
*/ */
protected String obtainUsername(HttpServletRequest req) { protected String obtainUsername(HttpServletRequest req) {
String claimedIdentity = req.getParameter(this.claimedIdentityFieldName); String claimedIdentity = req.getParameter(this.claimedIdentityFieldName);
if (!StringUtils.hasText(claimedIdentity)) { if (!StringUtils.hasText(claimedIdentity)) {
this.logger.error("No claimed identity supplied in authentication request"); this.logger.error("No claimed identity supplied in authentication request");
return ""; return "";
} }
return claimedIdentity.trim(); return claimedIdentity.trim();
} }

View File

@ -66,43 +66,34 @@ public class OpenIDAuthenticationProvider implements AuthenticationProvider, Ini
@Override @Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) { if (!supports(authentication.getClass())) {
return null; return null;
} }
if (!(authentication instanceof OpenIDAuthenticationToken)) {
if (authentication instanceof OpenIDAuthenticationToken) { return null;
}
OpenIDAuthenticationToken response = (OpenIDAuthenticationToken) authentication; OpenIDAuthenticationToken response = (OpenIDAuthenticationToken) authentication;
OpenIDAuthenticationStatus status = response.getStatus(); OpenIDAuthenticationStatus status = response.getStatus();
// handle the various possibilities // handle the various possibilities
if (status == OpenIDAuthenticationStatus.SUCCESS) { if (status == OpenIDAuthenticationStatus.SUCCESS) {
// Lookup user details // Lookup user details
UserDetails userDetails = this.userDetailsService.loadUserDetails(response); UserDetails userDetails = this.userDetailsService.loadUserDetails(response);
return createSuccessfulAuthentication(userDetails, response); return createSuccessfulAuthentication(userDetails, response);
} }
else if (status == OpenIDAuthenticationStatus.CANCELLED) { if (status == OpenIDAuthenticationStatus.CANCELLED) {
throw new AuthenticationCancelledException("Log in cancelled"); throw new AuthenticationCancelledException("Log in cancelled");
} }
else if (status == OpenIDAuthenticationStatus.ERROR) { if (status == OpenIDAuthenticationStatus.ERROR) {
throw new AuthenticationServiceException("Error message from server: " + response.getMessage()); throw new AuthenticationServiceException("Error message from server: " + response.getMessage());
} }
else if (status == OpenIDAuthenticationStatus.FAILURE) { if (status == OpenIDAuthenticationStatus.FAILURE) {
throw new BadCredentialsException("Log in failed - identity could not be verified"); throw new BadCredentialsException("Log in failed - identity could not be verified");
} }
else if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) { if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) {
throw new AuthenticationServiceException( throw new AuthenticationServiceException("The server responded setup was needed, which shouldn't happen");
"The server responded setup was needed, which shouldn't happen");
} }
else {
throw new AuthenticationServiceException("Unrecognized return value " + status.toString()); throw new AuthenticationServiceException("Unrecognized return value " + status.toString());
} }
}
return null;
}
/** /**
* Handles the creation of the final <tt>Authentication</tt> object which will be * Handles the creation of the final <tt>Authentication</tt> object which will be

View File

@ -63,7 +63,6 @@ public class OpenIDAuthenticationToken extends AbstractAuthenticationToken {
* Created by the <tt>OpenIDAuthenticationProvider</tt> on successful authentication. * Created by the <tt>OpenIDAuthenticationProvider</tt> on successful authentication.
* @param principal usually the <tt>UserDetails</tt> returned by the configured * @param principal usually the <tt>UserDetails</tt> returned by the configured
* <tt>UserDetailsService</tt> used by the <tt>OpenIDAuthenticationProvider</tt>. * <tt>UserDetailsService</tt> used by the <tt>OpenIDAuthenticationProvider</tt>.
*
*/ */
public OpenIDAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities, public OpenIDAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities,
String identityUrl, List<OpenIDAttribute> attributes) { String identityUrl, List<OpenIDAttribute> attributes) {

View File

@ -57,7 +57,6 @@ public class RegexBasedAxFetchListFactory implements AxFetchListFactory {
return entry.getValue(); return entry.getValue();
} }
} }
return Collections.emptyList(); return Collections.emptyList();
} }