Package org.apache.oltu.oauth2.common.parameters

Examples of org.apache.oltu.oauth2.common.parameters.WWWAuthHeaderParametersApplier



    @Test
    public void testTokenResponse() throws Exception {

        OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token")
            .setExpiresIn("200").setRefreshToken("refresh_token2")
            .buildBodyMessage();

        String body = oAuthResponse.getBody();
        Assert.assertEquals(
            "expires_in=200&refresh_token=refresh_token2&access_token=access_token",
            body);

    }
View Full Code Here


    }

    @Test
    public void testTokenResponseAdditionalParam() throws Exception {

        OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token")
            .setExpiresIn("200").setRefreshToken("refresh_token2").setParam("some_param", "new_param")
            .buildBodyMessage();

        String body = oAuthResponse.getBody();
        Assert.assertEquals(
            "some_param=new_param&expires_in=200&refresh_token=refresh_token2&access_token=access_token",
            body);

    }
View Full Code Here

            .error(OAuthError.CodeResponse.ACCESS_DENIED, "Access denied")
            .setParameter("testparameter", "testparameter_value")
            .scope("album")
            .uri("http://www.example.com/error");

        OAuthResponse oAuthResponse = OAuthResponse.errorResponse(400).error(ex).buildJSONMessage();

        Assert.assertEquals(
            "{\"error_uri\":\"http:\\/\\/www.example.com\\/error\",\"error\":\"access_denied\",\""
                + "error_description\":\"Access denied\"}",
            oAuthResponse.getBody());


        oAuthResponse = OAuthResponse.errorResponse(500)
            .location("http://www.example.com/redirect?param2=true").error(ex).buildQueryMessage();
        Assert.assertEquals(
            "http://www.example.com/redirect?param2=true&error_uri=http%3A%2F%2Fwww.example.com%2Ferror"
                + "&error=access_denied&error_description=Access+denied",
            oAuthResponse.getLocationUri());
    }
View Full Code Here

            .error(OAuthError.CodeResponse.ACCESS_DENIED, "Access denied")
            .setParameter("testparameter", "testparameter_value")
            .scope("album")
            .uri("http://www.example.com/error");

        OAuthResponse oAuthResponse = OAuthResponse.errorResponse(500)
            .location("http://www.example.com/redirect?param2=true").error(ex).buildQueryMessage();
        Assert.assertEquals(
            "http://www.example.com/redirect?param2=true&error_uri=http%3A%2F%2Fwww.example.com%2Ferror"
                + "&error=access_denied&error_description=Access+denied",
            oAuthResponse.getLocationUri());
    }
View Full Code Here

    }

    @Test
    public void testHeaderResponse() throws Exception {
      HttpServletRequest request = createMock(HttpServletRequest.class);
        OAuthResponse oAuthResponse = OAuthASResponse.authorizationResponse(request,400).setCode("oauth_code")
            .setState("state_ok")
            .buildHeaderMessage();

        String header = oAuthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE);
        Assert.assertEquals("Bearer state=\"state_ok\",code=\"oauth_code\"", header);

        header = oAuthResponse.getHeaders().get(OAuth.HeaderType.WWW_AUTHENTICATE);
        Assert.assertEquals("Bearer state=\"state_ok\",code=\"oauth_code\"", header);
    }
View Full Code Here

public class OAuthResponseTest {


    @Test
    public void testErrorResponse() throws Exception {
        OAuthResponse oAuthResponse = OAuthResponse.errorResponse(400)
            .setError("error")
            .setRealm("album")
            .setState("ok")
            .setErrorDescription("error_description")
            .setErrorUri("http://example-uri")
            .setParam("param", "value")
            .buildJSONMessage();

        String body = oAuthResponse.getBody();
        Assert.assertEquals(
            "{\"error_uri\":\"http:\\/\\/example-uri\",\"error\":\"error\",\"param\":\"value\","
                + "\"realm\":\"album\",\"state\":\"ok\",\"error_description\":\"error_description\"}",
            body);
    }
View Full Code Here

        }
        // The request does not conform to the RFC, so we return a HTTP 400
        // with a reason.
        catch (OAuthProblemException e) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Validate that the user is requesting a "code" response type, which
        // is the only response type we accept.
        try {
            if (!ResponseType.CODE.toString().equals(oauthRequest.getResponseType())) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE)
                        .setErrorDescription("The response type must be '" +
                                             ResponseType.CODE.toString() +
                                             "' but was instead: "
                                             + oauthRequest.getResponseType())
                        .setState(oauthRequest.getState())
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }
        }
        catch (IllegalArgumentException e) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE)
                    .setErrorDescription("The response type is unknown: " + oauthRequest.getResponseType())
                    .setState(oauthRequest.getState())
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Make sure a redirect URI was given.
        if (oauthRequest.getRedirectURI() == null) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.CodeResponse.INVALID_REQUEST)
                    .setErrorDescription("A redirect URI must be given.")
                    .setState(oauthRequest.getState())
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Attempt to get the third-party.
        Application application = oAuth2MgmtService.getApplicationForClientId(oauthRequest.getClientId());
        // If the third-party is unknown, reject the request.
        if (application == null) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError
                    (OAuthError.CodeResponse.INVALID_REQUEST).setErrorDescription(
                        "The client ID is unknown: " + oauthRequest.getClientId()
            ).setState(oauthRequest.getState()).buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Create the temporary code to be granted or rejected by the user.
        AuthorizationCode code = oAuth2MgmtService.issueAuthorizationCode(application.getId(),
                                                                          oauthRequest.getScopes(),
View Full Code Here

        }
        // If the HTTP request was not a valid OAuth token request, then we
        // have no other choice but to reject it as a bad request.
        catch (OAuthProblemException e) {
            // Build the OAuth response.
            OAuthResponse oauthResponse = OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                    .buildJSONMessage();

            // Set the HTTP response status code from the OAuth response.
            response.setStatus(oauthResponse.getResponseStatus());

            // Return the error message.
            return oauthResponse.getBody();
        }

        // Attempt to get the client.
        Application application = oAuth2MgmtService.getApplicationForClientId(oauthRequest.getClientId());
        // If the client is unknown, respond as such.
        if (application == null) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription("The client is unknown: " + oauthRequest.getClientId())
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Get the given client secret.
        String applicationSecret = oauthRequest.getClientSecret();
        if (applicationSecret == null) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription("The client secret is required.")
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }
        // Make sure the client gave the right secret.
        else if (!applicationSecret.equals(application.sharedSecret)) {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription("The client secret is incorrect.")
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Get the grant-type.
        GrantType grantType;
        String grantTypeString = oauthRequest.getGrantType();
        if (GrantType.AUTHORIZATION_CODE.toString().equals(grantTypeString)) {
            grantType = GrantType.AUTHORIZATION_CODE;
        }
        else if (GrantType.CLIENT_CREDENTIALS.toString().equals(grantTypeString)) {
            grantType = GrantType.CLIENT_CREDENTIALS;
        }
        else if (GrantType.PASSWORD.toString().equals(grantTypeString)) {
            grantType = GrantType.PASSWORD;
        }
        else if (GrantType.REFRESH_TOKEN.toString().equals(grantTypeString)) {
            grantType = GrantType.REFRESH_TOKEN;
        }
        else {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_GRANT)
                    .setErrorDescription("The grant type is unknown: " + grantTypeString)
                    .buildJSONMessage();
            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Handle the different types of token requests.
        AuthorizationToken token;
        if (GrantType.AUTHORIZATION_CODE.equals(grantType)) {
            // Attempt to get the code.
            String codeString = oauthRequest.getCode();
            if (codeString == null) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("An authorization code must be given to be exchanged  for an authorization token.")
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Attempt to lookup the actual AuthorizationCode object.
            AuthorizationCode code = oAuth2MgmtService.getCode(codeString);
            // If the code doesn't exist, reject the request.
            if (code == null) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("The given authorization code is unknown: " + codeString)
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Verify that the client asking for a token is the same as the one
            // that requested the code.
            if (code.applicationId != application.getId()) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("This client is not allowed to reference this code: " + codeString)
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // If the code has expired, reject the request.
            if (System.currentTimeMillis() > code.expirationTime) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("The given authorization code has expired: " + codeString)
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Use the code to lookup the response information and error out if
            // a user has not yet verified it.
            AuthorizationCodeResponse codeResponse = oAuth2MgmtService.getResponse(code.code);
            if (codeResponse == null) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("A user has not yet verified the code: " + codeString)
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Determine if the user granted access and, if not, error out.
            if (!codeResponse.granted) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("The user denied the authorization: " + codeString)
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Create a new token.
            token = new AuthorizationToken(codeResponse);
        }
        // Handle a third-party refreshing an existing token.
        else if (GrantType.REFRESH_TOKEN.equals(grantType)) {
            // Get the refresh token from the request.
            String refreshToken = oauthRequest.getRefreshToken();
            if (refreshToken == null) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("A refresh token must be given to be exchanged for a new authorization token.")
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }
            // Use the refresh token to lookup the actual refresh token.
            AuthorizationToken currentToken = oAuth2MgmtService.getTokenFromRefreshToken(refreshToken);
            if (currentToken == null) {
                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("The refresh token is unknown.")
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Verify that the client asking for a token is the same as the one
            // that was issued the refresh token.
            // This is probably a very serious offense and should probably
            // raise some serious red flags!
            if (!oAuth2MgmtService.getApplicationForToken(currentToken).getId().equals(application.getId())) {

                // Create the OAuth response.
                OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_REQUEST)
                        .setErrorDescription("This token does not belong to this client.")
                        .buildJSONMessage();

                // Set the status and return the error message.
                response.setStatus(oauthResponse.getResponseStatus());
                return oauthResponse.getBody();
            }

            // Create a new authorization token from the current one.
            token = new AuthorizationToken(currentToken);
        }
        // If the grant-type is unknown, then we do not yet understand how
        // the request is built and, therefore, can do nothing more than
        // reject it via an OmhException.
        else {
            // Create the OAuth response.
            OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.UNSUPPORTED_GRANT_TYPE)
                    .setErrorDescription("The grant type must be one of '" + GrantType.AUTHORIZATION_CODE.toString() +
                        "' or '" + GrantType.REFRESH_TOKEN.toString() + "': " + grantType.toString())
                    .buildJSONMessage();

            // Set the status and return the error message.
            response.setStatus(oauthResponse.getResponseStatus());
            return oauthResponse.getBody();
        }

        // Store the new token.
        oAuth2MgmtService.storeToken(token);

        // Build the response.
        OAuthResponse oauthResponse = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(token.accessToken)
                .setExpiresIn(Long.valueOf(token.getExpirationIn() / 1000).toString())
                .setRefreshToken(token.refreshToken)
                .setTokenType(TokenType.BEARER.toString())
                .buildJSONMessage();

        // Set the status.
        response.setStatus(oauthResponse.getResponseStatus());

        // Set the content-type.
        response.setContentType("application/json");

        // Add the headers.
        Map<String, String> headers = oauthResponse.getHeaders();
        for (String headerKey : headers.keySet()) {
            response.addHeader(headerKey, headers.get(headerKey));
        }

        // Return the body.
        return oauthResponse.getBody();
    }
View Full Code Here

    }
    // The request does not conform to the RFC, so we return a HTTP 400
    // with a reason.
    catch(OAuthProblemException e) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .error(e)
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Validate that the user is requesting a "code" response type, which
    // is the only response type we accept.
    try {
      if(!
        ResponseType
          .CODE.toString().equals(oauthRequest.getResponseType())) {
       
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(CodeResponse.UNSUPPORTED_RESPONSE_TYPE)
            .setErrorDescription(
              "The response type must be '" +
                ResponseType.CODE.toString() +
                "' but was instead: " +
                oauthRequest.getResponseType())
            .setState(oauthRequest.getState())
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
    }
    catch(IllegalArgumentException e) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(CodeResponse.UNSUPPORTED_RESPONSE_TYPE)
          .setErrorDescription(
            "The response type is unknown: " +
              oauthRequest.getResponseType())
          .setState(oauthRequest.getState())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Make sure no redirect URI was given.
    if(oauthRequest.getRedirectURI() != null) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(CodeResponse.INVALID_REQUEST)
          .setErrorDescription(
            "A URI must not be given. Instead, the one given " +
              "when the account was created will be used.")
          .setState(oauthRequest.getState())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Attempt to get the third-party.
    ThirdParty thirdParty =
      ThirdPartyBin
        .getInstance().getThirdParty(oauthRequest.getClientId());
    // If the third-party is unknown, reject the request.
    if(thirdParty == null) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(CodeResponse.INVALID_REQUEST)
          .setErrorDescription(
            "The client ID is unknown: " +
              oauthRequest.getClientId())
          .setState(oauthRequest.getState())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Attempt to get the scopes.
    Set<String> scopes = oauthRequest.getScopes();
    if((scopes == null) || (scopes.size() == 0)) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(CodeResponse.INVALID_SCOPE)
          .setErrorDescription("A scope is required.")
          .setState(oauthRequest.getState())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
    // Validate the scopes.
    Registry registry = Registry.getInstance();
    for(String scope : scopes) {
      if(registry.getSchemas(scope, null, 0, 1).size() != 1) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(CodeResponse.INVALID_SCOPE)
            .setErrorDescription(
              "Each scope must be a known schema ID: " + scope)
            .setState(oauthRequest.getState())
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
    }
   
    // Create the temporary code to be granted or rejected by the user.
    AuthorizationCode code =
View Full Code Here

      }
    // If the HTTP request was not a valid OAuth token request, then we
    // have no other choice but to reject it as a bad request.
    catch(OAuthProblemException e) {
      // Build the OAuth response.
          OAuthResponse oauthResponse =
            OAuthResponse
                .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .error(e)
                .buildJSONMessage();

          // Set the HTTP response status code from the OAuth response.
          response.setStatus(oauthResponse.getResponseStatus());
         
          // Return the error message.
          return oauthResponse.getBody();
      }
   
    // Attempt to get the client.
    ThirdParty thirdParty =
      ThirdPartyBin
        .getInstance().getThirdParty(oauthRequest.getClientId());
    // If the client is unknown, respond as such.
    if(thirdParty == null) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(TokenResponse.INVALID_CLIENT)
          .setErrorDescription(
            "The client is unknown: " + oauthRequest.getClientId())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Get the given client secret.
    String thirdPartySecret = oauthRequest.getClientSecret();
    if(thirdPartySecret == null) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(TokenResponse.INVALID_CLIENT)
          .setErrorDescription("The client secret is required.")
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
    // Make sure the client gave the right secret.
    else if(! thirdPartySecret.equals(thirdParty.getSecret())) {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(TokenResponse.INVALID_CLIENT)
          .setErrorDescription("The client secret is incorrect.")
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Get the grant-type.
    GrantType grantType;
    String grantTypeString = oauthRequest.getGrantType();
    if(GrantType.AUTHORIZATION_CODE.toString().equals(grantTypeString)) {
      grantType = GrantType.AUTHORIZATION_CODE;
    }
    else if(GrantType.CLIENT_CREDENTIALS.toString().equals(grantTypeString)) {
      grantType = GrantType.CLIENT_CREDENTIALS;
    }
    else if(GrantType.PASSWORD.toString().equals(grantTypeString)) {
      grantType = GrantType.PASSWORD;
    }
    else if(GrantType.REFRESH_TOKEN.toString().equals(grantTypeString)) {
      grantType = GrantType.REFRESH_TOKEN;
    }
    else {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(TokenResponse.INVALID_GRANT)
          .setErrorDescription(
            "The grant type is unknown: " + grantTypeString)
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Handle the different types of token requests.
    AuthorizationToken token;
    if(GrantType.AUTHORIZATION_CODE.equals(grantType)) {
      // Attempt to get the code.
      String codeString = oauthRequest.getCode();
      if(codeString == null) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "An authorization code must be given to be " +
                "exchanged for an authorization token.")
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Attempt to lookup the actual AuthorizationCode object.
      AuthorizationCode code =
        AuthorizationCodeBin.getInstance().getCode(codeString);
      // If the code doesn't exist, reject the request.
      if(code == null) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "The given authorization code is unknown: " +
                codeString)
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Verify that the client asking for a token is the same as the one
      // that requested the code.
      if(! code.getThirdParty().getId().equals(thirdParty.getId())) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "This client is not allowed to reference this " +
                "code: " +
                codeString)
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }

      // If the code has expired, reject the request.
      if(System.currentTimeMillis() > code.getExpirationTime()) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "The given authorization code has expired: " +
                codeString)
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Use the code to lookup the response information and error out if
      // a user has not yet verified it.
      AuthorizationCodeResponse codeResponse =
        AuthorizationCodeResponseBin
          .getInstance().getResponse(code.getCode());
      if(codeResponse == null) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "A user has not yet verified the code: " +
                codeString)
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Determine if the user granted access and, if not, error out.
      if(! codeResponse.getGranted()) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "The user denied the authorization: " + codeString)
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Create a new token.
      token = new AuthorizationToken(codeResponse);
    }
    // Handle a third-party refreshing an existing token.
    else if(GrantType.REFRESH_TOKEN.equals(grantType)) {
      // Get the refresh token from the request.
      String refreshToken = oauthRequest.getRefreshToken();
      if(refreshToken == null) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "An refresh token must be given to be exchanged " +
                "for a new authorization token.")
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
      // Use the refresh token to lookup the actual refresh token.
      AuthorizationToken currentToken =
        AuthorizationTokenBin
          .getInstance().getTokenFromRefreshToken(refreshToken);
      if(currentToken == null) {
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription("The refresh token is unknown.")
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Verify that the client asking for a token is the same as the one
      // that was issued the refresh token.
      // This is probably a very serious offense and should probably
      // raise some serious red flags!
      if(!
        currentToken
          .getThirdParty().getId().equals(thirdParty.getId())) {
       
        // Create the OAuth response.
        OAuthResponse oauthResponse =
          OAuthASResponse
            .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(TokenResponse.INVALID_REQUEST)
            .setErrorDescription(
              "This token does not belong to this client.")
            .buildJSONMessage();
       
        // Set the status and return the error message.
        response.setStatus(oauthResponse.getResponseStatus());
        return oauthResponse.getBody();
      }
     
      // Create a new authorization token from the current one.
      token = new AuthorizationToken(currentToken);
    }
    // If the grant-type is unknown, then we do not yet understand how
    // the request is built and, therefore, can do nothing more than
    // reject it via an OmhException.
    else {
      // Create the OAuth response.
      OAuthResponse oauthResponse =
        OAuthASResponse
          .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
          .setError(TokenResponse.UNSUPPORTED_GRANT_TYPE)
          .setErrorDescription(
            "The grant type must be one of '" +
              GrantType.AUTHORIZATION_CODE.toString() +
              "' or '" +
              GrantType.REFRESH_TOKEN.toString() +
              "': " +
              grantType.toString())
          .buildJSONMessage();
     
      // Set the status and return the error message.
      response.setStatus(oauthResponse.getResponseStatus());
      return oauthResponse.getBody();
    }
   
    // Store the new token.
    AuthorizationTokenBin.getInstance().storeToken(token);
   
    // Build the response.
    OAuthResponse oauthResponse =
      OAuthASResponse
        .tokenResponse(HttpServletResponse.SC_OK)
        .setAccessToken(token.getAccessToken())
        .setExpiresIn(Long.valueOf(token.getExpirationIn() / 1000).toString())
        .setRefreshToken(token.getRefreshToken())
        .setTokenType(TokenType.BEARER.toString())
        .buildJSONMessage();
   
    // Set the status.
    response.setStatus(oauthResponse.getResponseStatus());
   
    // Set the content-type.
    response.setContentType("application/json");

    // Add the headers.
    Map<String, String> headers = oauthResponse.getHeaders();
    for(String headerKey : headers.keySet()) {
      response.addHeader(headerKey, headers.get(headerKey));
    }
   
    // Return the body.
    return oauthResponse.getBody();
  }
View Full Code Here

TOP

Related Classes of org.apache.oltu.oauth2.common.parameters.WWWAuthHeaderParametersApplier

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.