Auth token and embedded component

I have an embedded component (html-file) on an entity edit form and want to send GET/POST-requests from the htmls’ javascript to the REST v1 application portal interface (/app-portal/api). But since the anonymous requests have restricted functionality in the application, I tried to pass the user session id to the embedded component in URL string and to use it in requests’ parameter, but got an error 401 “Session not found”. How can I do it right?
My CUBA platform version is 6.3.4.

1 Like

Hi,

It can be done using the following HTML:

<html>
<head>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<script>
    var sessionId = "%sessionId%";

    $.ajax({
        url: "http://localhost:8080/app-portal/api/query.json?" +
        "e=sec$User" +
        "&q=select+c+from+sec$User+c" +
        "&s=" + sessionId +
        "&view=_local",
        dataType: "json",
        success: function (data) {
            console.log("Y!");

            window.alert("OK " + data.length);
        }
    });
</script>
</body>
</html>

And replace sessionId parameter with actual session id:

public class ExtAppMainWindow extends AppMainWindow {
    @Inject
    private Embedded restHtml;
    @Inject
    private UserSession userSession;

    @Override
    public void init(Map<String, Object> params) {
        super.init(params);

        byte[] html;
        try {
            html = IOUtils.toString(getClass().getResource("rest-js.html"))
                .replace("%sessionId%", userSession.getId().toString())
                .getBytes(StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("Unable to read resource");
        }

        restHtml.setType(Embedded.Type.BROWSER);
        restHtml.setSource(UUID.randomUUID() + ".html", new ByteArrayInputStream(html));
    }
}

Here, we should also replace http://localhost:8080/app-portal with URL of app-portal.

Please note, that this trick will work only if app and app-portal are modules of the same CUBA application, it will not work between two different apps, because they do not share user sessions.

Thanks, Yuriy
Your code works and I used similar method in my project.
The problem I described links to a project-specific REST API where the separate sessions registry is used.