io.swagger.models.auth.ApiKeyAuthDefinition Java Examples

The following examples show how to use io.swagger.models.auth.ApiKeyAuthDefinition. 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: 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 #2
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 #3
Source File: SwaggerAuthHandlerFactory.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private AuthHandler getAuthHandler(String name) {
    AuthHandler authHandler = this.authHandlers.get(name);
    if (authHandler != null) {
        return authHandler;
    }

    AuthProvider authProvider = getAuthProviderFactory().getAuthProviderByName(name);
    if (authProvider == null) {
        return null;
    }

    SecuritySchemeDefinition securityScheme = this.securitySchemes.get(name);
    if(securityScheme != null) {
     switch (securityScheme.getType()) {
         case "apiKey":
             ApiKeyAuthDefinition apiKeyAuthDefinition = (ApiKeyAuthDefinition) securityScheme;
             Location apiKeyLocation = Location.valueOf(apiKeyAuthDefinition.getIn().name());
             authHandler = ApiKeyAuthHandler.create(authProvider, apiKeyLocation, apiKeyAuthDefinition.getName());
             break;
         case "basic":
             authHandler = BasicAuthHandler.create(authProvider);
             break;
         case "oauth2":
             vertxLogger.warn("OAuth2 authentication has not been implemented yet!");
             break;
         default:
             vertxLogger.warn("SecurityScheme is not authorized : " + securityScheme.getType());
             break;
     }
     
	
     if (authHandler != null) {
         this.authHandlers.put(name, authHandler);
     }
    } else {
        vertxLogger.warn("No securityScheme definition in swagger file for auth provider: " + name);
    }

    return authHandler;
}
 
Example #4
Source File: AuthBuilder.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the defined apiKey is valid or not. Only apiKey definition with name as 'key' and
 * 'in' as 'query' are allowed"
 */
private boolean isValidApiKeyDefinition(ApiKeyAuthDefinition apiKeydef) {
  if (apiKeydef.getName().equalsIgnoreCase("key") || apiKeydef.getIn() == In.QUERY) {
    return true;
  } else {
    diagCollector.addDiag(
        Diag.warning(
            SimpleLocation.UNKNOWN,
            "apiKey '%s' is ignored. Only apiKey with 'name' as 'key' and 'in' as 'query' are "
                + "supported",
            apiKeydef.getName()));
    return false;
  }
}
 
Example #5
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private SecurityScheme convertApiKeySecurityScheme(SecuritySchemeDefinition definition) {
    SecurityScheme securityScheme = new SecurityScheme();
    ApiKeyAuthDefinition apiKeyAuthDefinition = (ApiKeyAuthDefinition) definition;

    securityScheme.setType(SecurityScheme.Type.APIKEY);
    securityScheme.setName(apiKeyAuthDefinition.getName());
    securityScheme.setIn(SecurityScheme.In.valueOf(apiKeyAuthDefinition.getIn().toString()));

    return securityScheme;
}
 
Example #6
Source File: SwaggerFactory.java    From dorado with Apache License 2.0 4 votes vote down vote up
public static Swagger getSwagger() {
	if (!swaggerEnable)
		return new Swagger();

	if (swagger != null)
		return swagger;

	Reader reader = new Reader(new Swagger());

	String[] packages = null;
	Class<?> mainClass = Dorado.mainClass;
	EnableSwagger enableSwagger = mainClass.getAnnotation(EnableSwagger.class);

	if (enableSwagger != null) {
		packages = enableSwagger.value();
	}

	if (packages == null || packages.length == 0) {
		packages = Dorado.serverConfig.scanPackages();
	}

	if (packages == null || packages.length == 0) {
		packages = new String[] { mainClass.getPackage().getName() };
	}

	if (packages == null || packages.length == 0) {
		throw new IllegalArgumentException("缺少scanPackages设置");
	}

	Set<Class<?>> classes = new HashSet<>();
	for (String pkg : packages) {
		try {
			classes.addAll(PackageScanner.scan(pkg));
		} catch (Exception ex) {
			// ignore this ex
		}
	}

	Swagger _swagger = reader.read(classes);
	_swagger.setSchemes(Arrays.asList(Scheme.HTTP, Scheme.HTTPS));

	ApiKey apiKey = apiContext.getApiKey();
	if (apiKey != null) {
		ApiKeyAuthDefinition apiKeyAuth = new ApiKeyAuthDefinition(apiKey.getName(),
				In.forValue(apiKey.getIn() == null ? "header" : apiKey.getIn()));
		_swagger.securityDefinition("auth", apiKeyAuth);

		List<SecurityRequirement> securityRequirements = new ArrayList<>();
		SecurityRequirement sr = new SecurityRequirement();
		sr.requirement("auth");
		securityRequirements.add(sr);
		_swagger.setSecurity(securityRequirements);
	}
	if (apiContext.getInfo() != null)
		_swagger.setInfo(apiContext.getInfo());

	swagger = _swagger;
	return _swagger;
}
 
Example #7
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));
  }
}
 
Example #8
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 #9
Source File: SwaggerContext.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static ApiKeyAuthDefinition apiKeyAuth(String name, In in) {
    return new ApiKeyAuthDefinition(name, in);
}