示例#1
0
  /**
   * The "token endpoint" as described in <a
   * href="http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-3.2">Section 3.2</a> of the
   * OAuth spec.
   *
   * @param authorization the HTTP Basic auth header.
   * @param formParameters the request parameters
   * @return the response
   */
  @POST
  @Path("/token")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes("application/x-www-form-urlencoded")
  public Response token(
      @HeaderParam("Authorization") String authorization,
      final MultivaluedMap<String, String> formParameters) {
    // Convert incoming parameters into internal form and validate them
    AccessTokenRequest accessTokenRequest =
        AccessTokenRequest.fromMultiValuedFormParameters(formParameters);
    BasicAuthCredentials credentials =
        BasicAuthCredentials.createCredentialsFromHeader(authorization);

    ValidationResponse vr = oAuth2Validator.validate(accessTokenRequest, credentials);
    if (!vr.valid()) {
      return sendErrorResponse(vr);
    }

    // The request looks valid, attempt to process
    String grantType = accessTokenRequest.getGrantType();
    AuthorizationRequest request;
    try {
      if (GRANT_TYPE_AUTHORIZATION_CODE.equals(grantType)) {
        request = authorizationCodeToken(accessTokenRequest);
      } else if (GRANT_TYPE_REFRESH_TOKEN.equals(grantType)) {
        request = refreshTokenToken(accessTokenRequest);
      } else if (GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
        request = clientCredentialToken(accessTokenRequest);
      } else if (GRANT_TYPE_PASSWORD.equals(grantType)) {
        request = passwordToken(accessTokenRequest);
      } else {
        return sendErrorResponse(ValidationResponse.UNSUPPORTED_GRANT_TYPE);
      }
    } catch (ValidationResponseException e) {
      return sendErrorResponse(e.v);
    }
    AccessToken token = createAccessToken(request, false);

    AccessTokenResponse response =
        new AccessTokenResponse(
            token.getToken(),
            BEARER,
            token.getExpiresIn(),
            token.getRefreshToken(),
            StringUtils.join(token.getScopes(), ' '));

    return Response.ok()
        .entity(response)
        .cacheControl(cacheControlNoStore())
        .header("Pragma", "no-cache")
        .build();
  }
示例#2
0
 private Response sendErrorResponse(ValidationResponse response) {
   return sendErrorResponse(response.getValue(), response.getDescription(), response.getStatus());
 }