Search in sources :

Example 11 with OAuthFlow

use of io.swagger.v3.oas.models.security.OAuthFlow in project carbon-apimgt by wso2.

the class OASParserUtil method setScopes.

private static void setScopes(final OpenAPI destOpenAPI, final Set<Scope> aggregatedScopes) {
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes = new Scopes();
    if (destOpenAPI.getComponents() != null && (securitySchemes = destOpenAPI.getComponents().getSecuritySchemes()) != null && (securityScheme = securitySchemes.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlow = securityScheme.getFlows().getImplicit()) != null) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : aggregatedScopes) {
            scopes.addString(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }
        oAuthFlow.setScopes(scopes);
        Map<String, Object> extensions = new HashMap<>();
        extensions.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
        oAuthFlow.setExtensions(extensions);
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) HashMap(java.util.HashMap) Scopes(io.swagger.v3.oas.models.security.Scopes) JSONObject(org.json.JSONObject) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme)

Example 12 with OAuthFlow

use of io.swagger.v3.oas.models.security.OAuthFlow in project carbon-apimgt by wso2.

the class OAS3ParserTest method testUpdateAPIDefinitionWithExtensions.

@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas3Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas3Parser, oas3Resources);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
    OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
    boolean isExtensionNotFound = openAPI.getExtensions() == null || !openAPI.getExtensions().containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY);
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, openAPI.getPaths().size());
    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        PathItem path = pathEntry.getValue();
        for (Operation operation : path.readOperations()) {
            Assert.assertFalse(operation.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }
    // check updated scopes in security definition
    Operation itemGet = openAPI.getPaths().get("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));
    // check available scopes in security definition
    SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get("default");
    OAuthFlow implicityOauth = securityScheme.getFlows().getImplicit();
    Assert.assertTrue(implicityOauth.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", implicityOauth.getScopes().get("newScope"));
    Assert.assertTrue(implicityOauth.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding = (Map<String, String>) implicityOauth.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) OpenAPI(io.swagger.v3.oas.models.OpenAPI) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Test(org.junit.Test)

Example 13 with OAuthFlow

use of io.swagger.v3.oas.models.security.OAuthFlow in project carbon-apimgt by wso2.

the class OAS3Parser method getScopes.

/**
 * 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 {
    OpenAPI openAPI = getOpenAPI(resourceConfigsJSON);
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlows oAuthFlows;
    OAuthFlow oAuthFlow;
    Scopes scopes;
    if (openAPI.getComponents() != null && (securitySchemes = openAPI.getComponents().getSecuritySchemes()) != null) {
        Set<Scope> scopeSet = new HashSet<>();
        if ((securityScheme = securitySchemes.get(OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlows = securityScheme.getFlows()) != null && (oAuthFlow = oAuthFlows.getImplicit()) != null && (scopes = oAuthFlow.getScopes()) != null) {
            for (Map.Entry<String, String> entry : scopes.entrySet()) {
                Scope scope = new Scope();
                scope.setKey(entry.getKey());
                scope.setName(entry.getKey());
                scope.setDescription(entry.getValue());
                Map<String, String> scopeBindings;
                if (oAuthFlow.getExtensions() != null && (scopeBindings = (Map<String, String>) oAuthFlow.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS)) != null) {
                    if (scopeBindings.get(scope.getKey()) != null) {
                        scope.setRoles(scopeBindings.get(scope.getKey()));
                    }
                }
                scopeSet.add(scope);
            }
        } else if ((securityScheme = securitySchemes.get("OAuth2Security")) != null && (oAuthFlows = securityScheme.getFlows()) != null && (oAuthFlow = oAuthFlows.getPassword()) != null && (scopes = oAuthFlow.getScopes()) != null) {
            for (Map.Entry<String, String> entry : scopes.entrySet()) {
                Scope scope = new Scope();
                scope.setKey(entry.getKey());
                scope.setName(entry.getKey());
                scope.setDescription(entry.getValue());
                Map<String, String> scopeBindings;
                scopeSet.add(scope);
            }
        }
        return OASParserUtil.sortScopes(scopeSet);
    } else {
        return OASParserUtil.sortScopes(getScopesFromExtensions(openAPI));
    }
}
Also used : OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) Scopes(io.swagger.v3.oas.models.security.Scopes) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 14 with OAuthFlow

use of io.swagger.v3.oas.models.security.OAuthFlow in project carbon-apimgt by wso2.

the class OAS3Parser method checkAndSetEmptyScope.

/**
 * This is to avoid removing the `scopes` field of default security scheme when there are no scopes present. This
 * will set an empty scope object there.
 *
 *   securitySchemes:
 *     default:
 *       type: oauth2
 *       flows:
 *         implicit:
 *           authorizationUrl: 'https://test.com'
 *           scopes: {}
 *           x-scopes-bindings: {}
 *
 * @param swagger OpenAPI object
 */
private void checkAndSetEmptyScope(OpenAPI swagger) {
    Components comp = swagger.getComponents();
    Map<String, SecurityScheme> securitySchemeMap;
    SecurityScheme securityScheme;
    OAuthFlows oAuthFlows;
    OAuthFlow implicitFlow;
    if (comp != null && (securitySchemeMap = comp.getSecuritySchemes()) != null && (securityScheme = securitySchemeMap.get(OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlows = securityScheme.getFlows()) != null && (implicitFlow = oAuthFlows.getImplicit()) != null && implicitFlow.getScopes() == null) {
        implicitFlow.setScopes(new Scopes());
    }
}
Also used : Components(io.swagger.v3.oas.models.Components) OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) Scopes(io.swagger.v3.oas.models.security.Scopes) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme)

Example 15 with OAuthFlow

use of io.swagger.v3.oas.models.security.OAuthFlow in project openremote by openremote.

the class ManagerWebService method init.

@Override
public void init(Container container) throws Exception {
    super.init(container);
    String rootRedirectPath = getString(container.getConfig(), ROOT_REDIRECT_PATH, ROOT_REDIRECT_PATH_DEFAULT);
    // Modify swagger object mapper to match ours
    configureObjectMapper(Json.mapper());
    Json.mapper().addMixIn(ServerVariable.class, ServerVariableMixin.class);
    // Add swagger resource
    OpenAPI oas = new OpenAPI().servers(Collections.singletonList(new Server().url("/api/{realm}/").variables(new ServerVariables().addServerVariable("realm", new ServerVariable()._default("master"))))).schemaRequirement("openid", new SecurityScheme().type(SecurityScheme.Type.OAUTH2).flows(new OAuthFlows().authorizationCode(new OAuthFlow().authorizationUrl("/auth/realms/master/protocol/openid-connect/auth").refreshUrl("/auth/realms/master/protocol/openid-connect/token").tokenUrl("/auth/realms/master/protocol/openid-connect/token")))).security(Collections.singletonList(new SecurityRequirement().addList("openid")));
    Info info = new Info().title("OpenRemote Manager REST API").description("This is the documentation for the OpenRemote Manager HTTP REST API.  Please see the [wiki](https://github.com/openremote/openremote/wiki) for more info.").contact(new Contact().email("info@openremote.io")).license(new License().name("AGPL 3.0").url("https://www.gnu.org/licenses/agpl-3.0.en.html"));
    oas.info(info);
    SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourcePackages(Stream.of("org.openremote.model.*").collect(Collectors.toSet())).openAPI(oas);
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.openApiConfiguration(oasConfig);
    addApiSingleton(openApiResource);
    initialised = true;
    ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), apiSingletons, true);
    // Serve REST API
    HttpHandler apiHandler = createApiHandler(container, resteasyDeployment);
    if (apiHandler != null) {
        // Authenticating requests requires a realm, either we receive this in a header or
        // we extract it (e.g. from request path segment) and set it as a header before
        // processing the request
        HttpHandler baseApiHandler = apiHandler;
        apiHandler = exchange -> {
            String path = exchange.getRelativePath().substring(API_PATH.length());
            Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(path);
            if (!realmSubMatcher.matches()) {
                exchange.setStatusCode(NOT_FOUND.getStatusCode());
                throw new WebApplicationException(NOT_FOUND);
            }
            // Extract realm from path and push it into REQUEST_HEADER_REALM header
            String realm = realmSubMatcher.group(1);
            // Move the realm from path segment to header
            exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
            URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
            exchange.setRequestURI(url.toString(), true);
            exchange.setRequestPath(url.getPath());
            exchange.setRelativePath(url.getPath());
            baseApiHandler.handleRequest(exchange);
        };
    }
    // Serve deployment files unsecured (explicitly map deployment folders to request paths)
    builtInAppDocRoot = Paths.get(getString(container.getConfig(), APP_DOCROOT, APP_DOCROOT_DEFAULT));
    customAppDocRoot = Paths.get(getString(container.getConfig(), CUSTOM_APP_DOCROOT, CUSTOM_APP_DOCROOT_DEFAULT));
    HttpHandler defaultHandler = null;
    if (Files.isDirectory(customAppDocRoot)) {
        HttpHandler customBaseFileHandler = createFileHandler(container, customAppDocRoot, null);
        defaultHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            customBaseFileHandler.handleRequest(exchange);
        };
    }
    PathHandler deploymentHandler = defaultHandler != null ? new PathHandler(defaultHandler) : new PathHandler();
    // Serve deployment files
    if (Files.isDirectory(builtInAppDocRoot)) {
        HttpHandler appBaseFileHandler = createFileHandler(container, builtInAppDocRoot, null);
        HttpHandler appFileHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            // Reinstate the full path
            exchange.setRelativePath(exchange.getRequestPath());
            appBaseFileHandler.handleRequest(exchange);
        };
        deploymentHandler.addPrefixPath(MANAGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SWAGGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(CONSOLE_LOADER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SHARED_PATH, appFileHandler);
    }
    // Redirect / to default app
    if (rootRedirectPath != null) {
        getRequestHandlers().add(new RequestHandler("Default app redirect", exchange -> exchange.getRequestPath().equals("/"), exchange -> {
            LOG.finer("Handling root request, redirecting client to default app");
            new RedirectHandler(redirect(exchange, rootRedirectPath)).handleRequest(exchange);
        }));
    }
    if (apiHandler != null) {
        getRequestHandlers().add(pathStartsWithHandler("REST API Handler", API_PATH, apiHandler));
    }
    // This will try and handle any request that makes it to this handler
    getRequestHandlers().add(new RequestHandler("Deployment files", exchange -> true, deploymentHandler));
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Json(io.swagger.v3.core.util.Json) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) WebService(org.openremote.container.web.WebService) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) ValueUtil.configureObjectMapper(org.openremote.model.util.ValueUtil.configureObjectMapper) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ServletInfo(io.undertow.servlet.api.ServletInfo) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) RedirectHandler(io.undertow.server.handlers.RedirectHandler) Servlets(io.undertow.servlet.Servlets) HashSet(java.util.HashSet) License(io.swagger.v3.oas.models.info.License) PathHandler(io.undertow.server.handlers.PathHandler) Matcher(java.util.regex.Matcher) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI) io.swagger.v3.oas.models.security(io.swagger.v3.oas.models.security) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) URI(java.net.URI) Path(java.nio.file.Path) REALM_PARAM_NAME(org.openremote.model.Constants.REALM_PARAM_NAME) Files(java.nio.file.Files) Collection(java.util.Collection) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) Info(io.swagger.v3.oas.models.info.Info) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) HttpHandler(io.undertow.server.HttpHandler) Container(org.openremote.model.Container) IdentityService(org.openremote.container.security.IdentityService) Server(io.swagger.v3.oas.models.servers.Server) Stream(java.util.stream.Stream) Contact(io.swagger.v3.oas.models.info.Contact) Paths(java.nio.file.Paths) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) WebApplicationException(javax.ws.rs.WebApplicationException) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) RedirectBuilder.redirect(io.undertow.util.RedirectBuilder.redirect) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) HttpHandler(io.undertow.server.HttpHandler) Server(io.swagger.v3.oas.models.servers.Server) WebApplicationException(javax.ws.rs.WebApplicationException) Matcher(java.util.regex.Matcher) RedirectHandler(io.undertow.server.handlers.RedirectHandler) License(io.swagger.v3.oas.models.info.License) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) PathHandler(io.undertow.server.handlers.PathHandler) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) ServletInfo(io.undertow.servlet.api.ServletInfo) Info(io.swagger.v3.oas.models.info.Info) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) URI(java.net.URI) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) Contact(io.swagger.v3.oas.models.info.Contact) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Aggregations

OAuthFlow (io.swagger.v3.oas.models.security.OAuthFlow)15 Scopes (io.swagger.v3.oas.models.security.Scopes)13 SecurityScheme (io.swagger.v3.oas.models.security.SecurityScheme)12 OAuthFlows (io.swagger.v3.oas.models.security.OAuthFlows)10 OpenAPI (io.swagger.v3.oas.models.OpenAPI)8 HashMap (java.util.HashMap)7 LinkedHashMap (java.util.LinkedHashMap)7 Components (io.swagger.v3.oas.models.Components)6 Map (java.util.Map)6 SecurityRequirement (io.swagger.v3.oas.models.security.SecurityRequirement)4 ArrayList (java.util.ArrayList)4 Scope (org.wso2.carbon.apimgt.api.model.Scope)4 Operation (io.swagger.v3.oas.models.Operation)3 PathItem (io.swagger.v3.oas.models.PathItem)3 Info (io.swagger.v3.oas.models.info.Info)3 Server (io.swagger.v3.oas.models.servers.Server)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Contact (io.swagger.v3.oas.models.info.Contact)2 HashSet (java.util.HashSet)2 JSONObject (org.json.simple.JSONObject)2