001    /*
002     * Copyright 2012 UnboundID Corp.
003     *
004     * This program is free software; you can redistribute it and/or modify
005     * it under the terms of the GNU General Public License (GPLv2 only)
006     * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
007     * as published by the Free Software Foundation.
008     *
009     * This program is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012     * GNU General Public License for more details.
013     *
014     * You should have received a copy of the GNU General Public License
015     * along with this program; if not, see <http://www.gnu.org/licenses>.
016     */
017    package com.unboundid.scim.sdk;
018    
019    import org.apache.wink.client.ClientAuthenticationException;
020    import org.apache.wink.client.ClientRequest;
021    import org.apache.wink.client.ClientResponse;
022    import org.apache.wink.client.handlers.ClientHandler;
023    import org.apache.wink.client.handlers.HandlerContext;
024    import org.apache.wink.common.http.HttpStatus;
025    
026    /**
027     * This class provides OAuth Authentication handling.
028     */
029    public class OAuthSecurityHandler implements ClientHandler {
030      /**
031       * The stringified OAuth token authorization header.
032       */
033      private volatile String authorizationHeader;
034    
035      /**
036       * Constructs a fully initialized OAuthSecurityHandler handler.
037       * @param token Fully constructed OAuth Token
038       */
039      public OAuthSecurityHandler(final OAuthToken token) {
040        this.authorizationHeader = token.getFormattedValue();
041      }
042    
043      /**
044       * Attempts to authenticate a Consumer via OAuth tokens.
045       *
046       * @param request  The Client Resource request.
047       * @param context The provided handler chain.
048       * @return Client Response that may indicate success or failure.
049       * @throws Exception Thrown if error handling authentication.
050       */
051      public ClientResponse handle(final ClientRequest request,
052                                   final HandlerContext context) throws Exception {
053        request.getHeaders().putSingle("Authorization", this.authorizationHeader);
054        ClientResponse response = context.doChain(request);
055        if (response.getStatusCode() == HttpStatus.UNAUTHORIZED.getCode()) {
056          throw new ClientAuthenticationException(this.authorizationHeader);
057        } else {
058          // error presumably unrelated to authentication
059          return response;
060        }
061      }
062    }