io.swagger.models.auth.OAuth2Definition Java Examples

The following examples show how to use io.swagger.models.auth.OAuth2Definition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityDefinitionTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityDefinitionRetainsWantedName() throws GenerateException {
    SecurityDefinition definition = new SecurityDefinition();
    definition.setJson("securityDefinition.json");

    Map<String, SecuritySchemeDefinition> definitions = definition.generateSecuritySchemeDefinitions();

    SecuritySchemeDefinition api_key = definitions.get("api_key");
    Assert.assertNotNull(api_key);
    Assert.assertTrue(api_key instanceof ApiKeyAuthDefinition);
    Assert.assertEquals(((ApiKeyAuthDefinition)api_key).getName(), "api_key_name");

    // No name is set for this auth
    // The name should be set to the name of the definition
    // So that the name is never actually empty
    SecuritySchemeDefinition api_key_empty_name = definitions.get("api_key_empty_name");
    Assert.assertNotNull(api_key_empty_name);
    Assert.assertTrue(api_key_empty_name instanceof ApiKeyAuthDefinition);
    Assert.assertEquals(((ApiKeyAuthDefinition)api_key_empty_name).getName(), "api_key_empty_name");


    SecuritySchemeDefinition petstore_auth = definitions.get("petstore_auth");
    Assert.assertNotNull(petstore_auth);
    Assert.assertTrue(petstore_auth instanceof OAuth2Definition);
}
 
Example #2
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the "Auth2" security scheme key
 *
 * @param swagger Swgger object
 * @return "Auth2" security scheme key
 */
private String getOAuth2SecuritySchemeKey(Swagger swagger) {
    final String oauth2Type = new OAuth2Definition().getType();
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    boolean hasDefaultKey = false;
    boolean hasRESTAPIScopeKey = false;
    if (securityDefinitions != null) {
        for (Map.Entry<String, SecuritySchemeDefinition> definitionEntry : securityDefinitions.entrySet()) {
            if (oauth2Type.equals(definitionEntry.getValue().getType())) {
                //sets hasDefaultKey to true if at least once SWAGGER_APIM_DEFAULT_SECURITY becomes the key
                hasDefaultKey = hasDefaultKey || SWAGGER_APIM_DEFAULT_SECURITY.equals(definitionEntry.getKey());
                //sets hasRESTAPIScopeKey to true if at least once SWAGGER_APIM_RESTAPI_SECURITY becomes the key
                hasRESTAPIScopeKey = hasRESTAPIScopeKey
                        || SWAGGER_APIM_RESTAPI_SECURITY.equals(definitionEntry.getKey());
            }
        }
    }
    if (hasDefaultKey) {
        return SWAGGER_APIM_DEFAULT_SECURITY;
    } else if (hasRESTAPIScopeKey) {
        return SWAGGER_APIM_RESTAPI_SECURITY;
    } else {
        return null;
    }
}
 
Example #3
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Update swagger with security definition
 *
 * @param swagger     swagger object
 * @param swaggerData Swagger related data
 */
private void updateSwaggerSecurityDefinition(Swagger swagger, SwaggerData swaggerData, String authUrl) {
    OAuth2Definition oAuth2Definition = new OAuth2Definition().implicit(authUrl);
    Set<Scope> scopes = swaggerData.getScopes();
    if (scopes != null && !scopes.isEmpty()) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : scopes) {
            oAuth2Definition.addScope(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }
        oAuth2Definition.setVendorExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
    }
    swagger.addSecurityDefinition(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY, oAuth2Definition);
    if (swagger.getSecurity() == null) {
        SecurityRequirement securityRequirement = new SecurityRequirement();
        securityRequirement.setRequirements(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY, new ArrayList<String>());
        swagger.addSecurity(securityRequirement);
    }
}
 
Example #4
Source File: SecurityDefinitionDeserializer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override public SecuritySchemeDefinition deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    SecuritySchemeDefinition result = null;

    JsonNode node = jp.getCodec().readTree(jp);
    JsonNode inNode = node.get("type");

    if (inNode != null) {
        String type = inNode.asText();
        if ("basic".equals(type)) {
            result = Json.mapper().convertValue(node, BasicAuthDefinition.class);
        } else if ("apiKey".equals(type)) {
            result = Json.mapper().convertValue(node, ApiKeyAuthDefinition.class);
        } else if ("oauth2".equals(type)) {
            result = Json.mapper().convertValue(node, OAuth2Definition.class);
        }
    }

    return result;
}
 
Example #5
Source File: SwaggerGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static SecuritySchemeDefinition toScheme(
    IssuerConfig issuerConfig, ImmutableSet<String> audiences) {
  OAuth2Definition tokenDef = new OAuth2Definition().implicit("");
  tokenDef.setVendorExtension("x-google-issuer", issuerConfig.getIssuer());
  if (!com.google.common.base.Strings.isNullOrEmpty(issuerConfig.getJwksUri())) {
    tokenDef.setVendorExtension("x-google-jwks_uri", issuerConfig.getJwksUri());
  }
  tokenDef.setVendorExtension("x-google-audiences", COMMA_JOINER.join(audiences));
  return tokenDef;
}
 
Example #6
Source File: OAS2ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas2" + File.separator + "oas2Resources.json";
    String oas2Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    SwaggerParser swaggerParser = new SwaggerParser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas2Parser, oas2Resources);
    Swagger swaggerObj = swaggerParser.parse(definition);
    boolean isExtensionNotFound =
            swaggerObj.getVendorExtensions() == null || swaggerObj.getVendorExtensions().isEmpty();
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, swaggerObj.getPaths().size());

    Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Path> pathEntry = itr.next();
        Path path = pathEntry.getValue();
        for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
            Operation operation = operationEntry.getValue();
            Assert.assertFalse(operation.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = swaggerObj.getPath("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    OAuth2Definition oAuth2Definition = (OAuth2Definition) swaggerObj.getSecurityDefinitions().get("default");
    Assert.assertTrue(oAuth2Definition.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", oAuth2Definition.getScopes().get("newScope"));

    Assert.assertTrue(oAuth2Definition.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding = (Map<String, String>) oAuth2Definition.getVendorExtensions()
            .get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
 
Example #7
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the boolean value which checks whether the swagger is included default security scheme or not
 *
 * @param swaggerContent resource json
 * @return boolean
 * @throws APIManagementException
 */
private boolean isDefaultGiven(String swaggerContent) throws APIManagementException {
    Swagger swagger = getSwagger(swaggerContent);

    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    if (securityDefinitions == null) {
        return false;
    }
    OAuth2Definition checkDefault = (OAuth2Definition) securityDefinitions.get(SWAGGER_SECURITY_SCHEMA_KEY);
    if (checkDefault == null) {
        return false;
    }
    return true;
}
 
Example #8
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the oauth scopes according to the given swagger
 *
 * @param resourceConfigsJSON resource json
 * @return scope set
 * @throws APIManagementException
 */
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
    Swagger swagger = getSwagger(resourceConfigsJSON);
    String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);

    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    OAuth2Definition oAuth2Definition;
    if (securityDefinitions != null
            && (oAuth2Definition = (OAuth2Definition) securityDefinitions.get(oauth2SchemeKey)) != null
            && oAuth2Definition.getScopes() != null) {
        Set<Scope> scopeSet = new LinkedHashSet<>();
        for (Map.Entry<String, String> entry : oAuth2Definition.getScopes().entrySet()) {
            Scope scope = new Scope();
            scope.setKey(entry.getKey());
            scope.setName(entry.getKey());
            scope.setDescription(entry.getValue());
            Map<String, String> scopeBindings;
            if (oAuth2Definition.getVendorExtensions() != null && (scopeBindings =
                    (Map<String, String>) oAuth2Definition.getVendorExtensions()
                            .get(APIConstants.SWAGGER_X_SCOPES_BINDINGS)) != null) {
                if (scopeBindings.get(scope.getKey()) != null) {
                    scope.setRoles(scopeBindings.get(scope.getKey()));
                }
            }
            scopeSet.add(scope);
        }
        return OASParserUtil.sortScopes(scopeSet);
    } else {
        return OASParserUtil.sortScopes(getScopesFromExtensions(swagger));
    }
}
 
Example #9
Source File: SecurityDefinitionConfigurator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void afterScan(Reader reader, Swagger swagger) {
    OAuth2Definition tokenScheme = new OAuth2Definition();
    tokenScheme.setType("oauth2");
    tokenScheme.setFlow("application");
    tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth2/token");
    tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth2/authorize");
    tokenScheme.addScope("write:everything", "Full access");

    Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
    schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);

    swagger.setSecurityDefinitions(schemes);
   //TODO: Have to add wso2-scopes to swagger definition from here
}
 
Example #10
Source File: SecurityDefinitionConfigurator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void afterScan(Reader reader, Swagger swagger) {
    OAuth2Definition tokenScheme = new OAuth2Definition();
    tokenScheme.setType("oauth2");
    tokenScheme.setFlow("application");
    tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth2/token");
    tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth2/authorize");
    tokenScheme.addScope("write:everything", "Full access");

    Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
    schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);

    swagger.setSecurityDefinitions(schemes);
   //TODO: Have to add wso2-scopes to swagger definition from here
}
 
Example #11
Source File: SecurityDefinitionConfigurator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void afterScan(Reader reader, Swagger swagger) {
    OAuth2Definition tokenScheme = new OAuth2Definition();
    tokenScheme.setType("oauth2");
    tokenScheme.setFlow("application");
    tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth2/token");
    tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth2/authorize");
    tokenScheme.addScope("write:everything", "Full access");

    Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
    schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);

    swagger.setSecurityDefinitions(schemes);
}
 
Example #12
Source File: SecurityDefinitionConfigurator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void afterScan(Reader reader, Swagger swagger) {
    OAuth2Definition tokenScheme = new OAuth2Definition();
    tokenScheme.setType("oauth2");
    tokenScheme.setFlow("application");
    tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth2/token");
    tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth2/authorize");
    tokenScheme.addScope("write:everything", "Full access");

    Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
    schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);

    swagger.setSecurityDefinitions(schemes);
}
 
Example #13
Source File: SwaggerServletContextListener.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private BeanConfig getBeanConfig() {
    BeanConfig beanConfig = new BeanConfig();
    beanConfig.setHost(getConfig("swagger.host"));
    beanConfig.setSchemes(getConfig("swagger.schemes").split(","));
    beanConfig.setTitle(getConfig("swagger.title"));
    beanConfig.setVersion(getConfig("swagger.version"));
    beanConfig.setContact(getConfig("swagger.contact"));
    beanConfig.setLicense(getConfig("swagger.license"));
    beanConfig.setBasePath(getConfig("swagger.base_path"));
    beanConfig.setLicenseUrl(getConfig("swagger.licenseUrl"));
    beanConfig.setDescription(getConfig("swagger.description"));
    beanConfig.setPrettyPrint(getConfig("swagger.pretty_print"));
    beanConfig.setTermsOfServiceUrl(getConfig("swagger.terms_of_service_url"));

    // Must be called last
    beanConfig.setResourcePackage(resourcePackages());
    beanConfig.setScan(true);

    Swagger swagger = beanConfig.getSwagger();

    if ("basic".equals(getConfig("webServer.securityHandlerType"))) {
        swagger.securityDefinition("eddi_auth", new BasicAuthDefinition());
    } else if ("keycloak".equals(getConfig("webServer.securityHandlerType"))) {
        OAuth2Definition oAuth2Definition = new OAuth2Definition()
                .implicit(getConfig("swagger.oauth2.implicitAuthorizationUrl"));
        oAuth2Definition.setDescription("client_id is 'eddi-engine'");
        swagger.securityDefinition("eddi_auth", oAuth2Definition);
    }

    return beanConfig;
}
 
Example #14
Source File: SwaggerContext.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static OAuth2Definition oAuth2() {
    return new OAuth2Definition();
}
 
Example #15
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
private SecurityScheme convertOauth2SecurityScheme(SecuritySchemeDefinition definition) {
    SecurityScheme securityScheme = new SecurityScheme();
    OAuth2Definition oAuth2Definition = (OAuth2Definition) definition;
    OAuthFlows oAuthFlows = new OAuthFlows();
    OAuthFlow oAuthFlow = new OAuthFlow();

    securityScheme.setType(SecurityScheme.Type.OAUTH2);
    String flow = oAuth2Definition.getFlow();

    if (flow != null) {
        switch (flow) {
            case "implicit":
                oAuthFlow.setAuthorizationUrl(oAuth2Definition.getAuthorizationUrl());
                oAuthFlows.setImplicit(oAuthFlow);
                break;
            case "password":
                oAuthFlow.setTokenUrl(oAuth2Definition.getTokenUrl());
                oAuthFlows.setPassword(oAuthFlow);
                break;
            case "application":
                oAuthFlow.setTokenUrl(oAuth2Definition.getTokenUrl());
                oAuthFlows.setClientCredentials(oAuthFlow);
                break;
            case "accessCode":
                oAuthFlow.setAuthorizationUrl(oAuth2Definition.getAuthorizationUrl());
                oAuthFlow.setTokenUrl(oAuth2Definition.getTokenUrl());
                oAuthFlows.setAuthorizationCode(oAuthFlow);
                break;
        }
    }

    Scopes scopes = new Scopes();
    Map<String, String> oAuth2Scopes = oAuth2Definition.getScopes();
    if (oAuth2Scopes != null) {
        oAuth2Scopes.forEach((k, v) -> scopes.addString(k, v));
    }
    oAuthFlow.setScopes(scopes);

    securityScheme.setFlows(oAuthFlows);

    return securityScheme;
}
 
Example #16
Source File: SecuritySchemeDefinitionComponent.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
private MarkupDocBuilder buildSecurityScheme(MarkupDocBuilder markupDocBuilder, SecuritySchemeDefinition securityScheme) {
    String type = securityScheme.getType();
    MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);

    paragraphBuilder.italicText(labels.getLabel(TYPE)).textLine(COLON + type);

    if (securityScheme instanceof ApiKeyAuthDefinition) {
        paragraphBuilder.italicText(labels.getLabel(NAME)).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getName());
        paragraphBuilder.italicText(labels.getLabel(IN)).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getIn());

        return markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
    } else if (securityScheme instanceof OAuth2Definition) {
        OAuth2Definition oauth2Scheme = (OAuth2Definition) securityScheme;
        String flow = oauth2Scheme.getFlow();
        paragraphBuilder.italicText(labels.getLabel(FLOW)).textLine(COLON + flow);
        if (isNotBlank(oauth2Scheme.getAuthorizationUrl())) {
            paragraphBuilder.italicText(labels.getLabel(AUTHORIZATION_URL)).textLine(COLON + oauth2Scheme.getAuthorizationUrl());
        }
        if (isNotBlank(oauth2Scheme.getTokenUrl())) {
            paragraphBuilder.italicText(labels.getLabel(TOKEN_URL)).textLine(COLON + oauth2Scheme.getTokenUrl());
        }

        markupDocBuilder.paragraph(paragraphBuilder.toString(), true);

        if (oauth2Scheme.getScopes() != null && !oauth2Scheme.getScopes().isEmpty()) {
            StringColumn.Builder nameColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(NAME_COLUMN)))
                    .putMetaData(TableComponent.WIDTH_RATIO, "3")
                    .putMetaData(TableComponent.HEADER_COLUMN, "true");
            StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
                    .putMetaData(TableComponent.WIDTH_RATIO, "17")
                    .putMetaData(TableComponent.HEADER_COLUMN, "true");

            for (Map.Entry<String, String> scope : oauth2Scheme.getScopes().entrySet()) {
                nameColumnBuilder.add(scope.getKey());
                descriptionColumnBuilder.add(scope.getValue());
            }

            return tableComponent.apply(markupDocBuilder, TableComponent.parameters(nameColumnBuilder.build(),
                    descriptionColumnBuilder.build()));
        } else {

            return markupDocBuilder;
        }

    } else {
        return markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
    }
}
 
Example #17
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the oauth scopes according to the given swagger(version 2)
 *
 * @param swagger resource json
 * @return Swagger
 * @throws APIManagementException
 */
private Swagger injectOtherScopesToDefaultScheme(Swagger swagger) throws APIManagementException {
    //Get security definitions from swagger
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    List<String> otherSetOfSchemes = new ArrayList<>();
    Map<String, String> defaultScopeBindings = null;
    if (securityDefinitions != null) {
        //If there is no default type schemes set a one
        OAuth2Definition newDefault = new OAuth2Definition();
        securityDefinitions.put(SWAGGER_SECURITY_SCHEMA_KEY, newDefault);
        //Check all the security definitions
        for (Map.Entry<String, SecuritySchemeDefinition> definition : securityDefinitions.entrySet()) {
            String checkType = definition.getValue().getType();
            //Inject other scheme scopes into default scope
            if (!SWAGGER_SECURITY_SCHEMA_KEY.equals(definition.getKey()) && "oauth2".equals(checkType)) {
                //Add non default scopes to other scopes list
                otherSetOfSchemes.add(definition.getKey());
                //Check for default one
                OAuth2Definition noneDefaultFlowType = (OAuth2Definition) definition.getValue();
                OAuth2Definition defaultTypeFlow = (OAuth2Definition) securityDefinitions.get(SWAGGER_SECURITY_SCHEMA_KEY);
                Map<String, String> noneDefaultFlowScopes = noneDefaultFlowType.getScopes();
                Map<String, String> defaultTypeScopes = defaultTypeFlow.getScopes();
                if (defaultTypeScopes == null) {
                    defaultTypeScopes = new HashMap<>();
                }
                for (Map.Entry<String, String> input : noneDefaultFlowScopes.entrySet()) {
                    defaultTypeScopes.put(input.getKey(), input.getValue());
                }
                defaultTypeFlow.setScopes(defaultTypeScopes);
                //Check X-Scope Bindings
                Map<String, String> noneDefaultScopeBindings = null;
                Map<String, Object> defaultTypeExtension = defaultTypeFlow.getVendorExtensions();
                if (noneDefaultFlowType.getVendorExtensions() != null && (noneDefaultScopeBindings =
                        (Map<String, String>) noneDefaultFlowType.getVendorExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS))
                        != null) {
                    if (defaultScopeBindings == null) {
                        defaultScopeBindings = new HashMap<>();
                    }
                    //Inject non default scope bindings into default scheme
                    for (Map.Entry<String, String> roleInUse : noneDefaultScopeBindings.entrySet()) {
                        defaultScopeBindings.put(roleInUse.getKey(), roleInUse.getValue());
                    }
                }
                defaultTypeExtension.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, defaultScopeBindings);
                defaultTypeFlow.setVendorExtensions(defaultTypeExtension);
                securityDefinitions.put(SWAGGER_SECURITY_SCHEMA_KEY, defaultTypeFlow);
            }
        }
        //update list of security schemes in the swagger object
        swagger.setSecurityDefinitions(securityDefinitions);
    }
    setOtherSchemes(otherSetOfSchemes);
    return swagger;
}
 
Example #18
Source File: AuthBuilder.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
/** Creates {@link AuthProvider} from Swagger SecuritySchemeDefinition. */
private void addAuthProvider(
    Service.Builder serviceBuilder,
    String securitySchemaName,
    SecuritySchemeDefinition securitySchema) {
  if (securitySchema == null) {
    return;
  }

  if (securitySchema.getType().equalsIgnoreCase("oauth2")) {
    OAuth2Definition oauthSchema = (OAuth2Definition) securitySchema;
    AuthProvider.Builder authProviderBuilder = AuthProvider.newBuilder();
    authProviderBuilder.setId(securitySchemaName);
    String oauthIssuerSwaggerExtensionUsed =
        VendorExtensionUtils.usedExtension(
            diagCollector,
            securitySchema.getVendorExtensions(),
            ExtensionNames.OAUTH_ISSUER_SWAGGER_EXTENSION,
            ExtensionNames.OAUTH_ISSUER_SWAGGER_EXTENSION_LEGACY);
    if (!Strings.isNullOrEmpty(oauthIssuerSwaggerExtensionUsed)) {
      String oauthIssuerSwaggerExtensionObject =
          VendorExtensionUtils.getExtensionValue(
              securitySchema.getVendorExtensions(),
              String.class,
              diagCollector,
              oauthIssuerSwaggerExtensionUsed);

      if (oauthIssuerSwaggerExtensionObject != null) {
        authProviderBuilder.setIssuer(oauthIssuerSwaggerExtensionObject);
      }
    }
    if (oauthSchema.getAuthorizationUrl() != null) {
      authProviderBuilder.setAuthorizationUrl(oauthSchema.getAuthorizationUrl());
    }
    String jwksSwaggerExtensionUsed =
        VendorExtensionUtils.usedExtension(
            diagCollector,
            securitySchema.getVendorExtensions(),
            ExtensionNames.JWKS_SWAGGER_EXTENSION,
            ExtensionNames.JWKS_SWAGGER_EXTENSION_LEGACY);
    if (!Strings.isNullOrEmpty(jwksSwaggerExtensionUsed)) {
      String jwksSwaggerExtensionValue =
          VendorExtensionUtils.getExtensionValue(
              securitySchema.getVendorExtensions(),
              String.class,
              diagCollector,
              jwksSwaggerExtensionUsed);
      if (jwksSwaggerExtensionValue != null) {
        authProviderBuilder.setJwksUri(jwksSwaggerExtensionValue);
      }
    }

    String audiencesSwaggerExtensionUsed =
        VendorExtensionUtils.usedExtension(
            diagCollector,
            securitySchema.getVendorExtensions(),
            ExtensionNames.AUDIENCES_SWAGGER_EXTENSION);
    if (!Strings.isNullOrEmpty(audiencesSwaggerExtensionUsed)) {
      String audiencesSwaggerExtensionValue =
          VendorExtensionUtils.getExtensionValue(
              securitySchema.getVendorExtensions(),
              String.class,
              diagCollector,
              audiencesSwaggerExtensionUsed);
      if (audiencesSwaggerExtensionValue != null) {
        authProviderBuilder.setAudiences(audiencesSwaggerExtensionValue);
      }
    }

    Authentication.Builder authenticationBuilder = serviceBuilder.getAuthenticationBuilder();
    authenticationBuilder.addProviders(authProviderBuilder.build());
    authRuleGenerator.registerAuthSchemaName(securitySchemaName);
  } else if (securitySchema.getType().equalsIgnoreCase("apiKey")) {
    ApiKeyAuthDefinition apiKeyDef = (ApiKeyAuthDefinition) securitySchema;
    if (isValidApiKeyDefinition(apiKeyDef)) {
      apiKeyDefinitions.add(securitySchemaName);
    }
  } else {
    diagCollector.addDiag(
        Diag.warning(
            SimpleLocation.UNKNOWN,
            "Security Schema '%s' is not supported. Only support schema are OAuth2",
            securitySchemaName));
  }
}