Authenticate users for apps outside of Splunk Web

For your apps that run outside of Splunk Web, you'll need to create a custom process to log users into the Splunk server. Use the Splunk SDK for JavaScript (included with SplunkJS Stack) or use the Splunk REST API to connect to Splunk and get a session key. Then, in the SplunkJS Stack configuration section of your app, you must define an authenticate function to use this session key along with the corresponding username so that your app's user can interact with Splunk.

The session key is valid for one hour, but is refreshed every time you make a call to the Splunk server. When the session times out or if the user logs out, an onSessionExpired function calls the authenticate function to log in again. You can modify the onSessionExpired function if you want custom behavior.

Example

The following example shows how to use the Splunk SDK for JavaScript to connect to Splunk. This example separates the process into two pages: a login form takes login credentials to authenticate with Splunk and get a session key, and another page uses this session key to interact with Splunk.

login_form.html

This page uses the Splunk SDK for JavaScript to authenticate user credentials with the Splunk server. If login is successful, a session key is returned and stored in a cookie, along with the username. Then, this page redirects to the login_verify.html page to use the session key.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Login Tests</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" type="text/css" href="static/splunkjs/css/bootstrap.css"/>
    <style type="text/css">
        .fail{
            color: red;
        }
        .main-area {
            padding: 30px;
        }
    </style>
</head>

<body>
    <div class="main-area">
        <h2>Login Form</h2>
        <p>This page tests login and authentication. When you enter a 
            name and password, these credentials are used to log in 
            to Splunk.</p>
        <p>If login is successful, a session key is returned and stored 
            in a cookie, along with the username. Then, you are redirected 
            to another page that uses the same session key.</p>
        <br>
        <p><b>Username:</b></p>
        <input id="usernamebox" type="text">
        <p><b>Password:</b></p>
        <input id="pwbox" type="password">
        <br>
        <button class="btn" onclick="onLogin()">Log in</button>
        <br>
        <div id="errorText"></div>
    </div>

    <script src="static/splunkjs/config.js"></script>

    <script>
        // Set the web site's base URL
        require.config({
            baseUrl: "static/"
        });

        // Log In button function
        function onLogin() {
            require([
                "jquery",
                "splunkjs/splunk",
            ], function($, jssdk) {
                // Get the username and passwords
                var username = $("#usernamebox").val();
                var password = $("#pwbox").val();

                // Use the Splunk SDK for JavaScript to log in to Splunk

                // Create a Service object
                var http =  new jssdk.ProxyHttp("/proxy");
                var service = new jssdk.Service(http, {
                    username: username,
                    password: password,
                    scheme: "https",
                    host: "localhost", 
                    port: 8089
                });
            
                // Log in to Splunk
                service.login(function(err) {
                    // The session key and username are required for logging in
                    if (!err) {
                        var key = service.sessionKey;
                        // Save the session key and username in cookies
                        $.cookie("splunk_sessionkey", key);
                        $.cookie("splunk_username", username);

                        // Redirect to another page
                        window.location.href = "login_verify.html";  
                    }
                    else {
                        $("#errorText").empty().append("<p class='fail'><br>Login failed! See the console for error info.</p>");
                        console.error("Login failed: ", err);
                    }              
                });
            });
        }   
    </script>
</body>
</html>

login_verify.html

This page uses the stored session key and username from the login form above to log in and interact with Splunk. If the session key expires (for example, by clicking the Log out button), this page redirects to login_form.html. The Splunk SDK for JavaScript is used in this example to log out of Splunk.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Login Tests</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="static/splunkjs/css/bootstrap.css"/>
    <style type="text/css">
        .main-area {
            padding: 30px;
        }
    </style>
</head>

<body>
    <div class="main-area">
        <h2>Verify Login</h2>
        <p>This page logs into Splunk using an existing session key. If a valid session key is not provided (the session expires, you log out, or you haven't logged in yet), you are redirected to the Login Form page to get a new session key.</p>
        <br>
        <p>The session key is used any time you interact with the Splunk server. The search in the table below uses a real-time 30 second window, so the session key is used frequently.</p>
        <p>If you see a table below, you are logged in:</p>
        <div id="table1"></div>
        <br>
        <p>Log out manually by deleting the session key:</p>
        <button id="logout" class="btn">Log out</button>
    </div>

    <script src="static/splunkjs/config.js"></script>

    <script>
        // Configure the web site's base URL
        require.config({
            baseUrl: "static/"
        });

        var splunkSessionKey;
        var splunkCurrentUser;

        // Configure SplunkJS Stack
        splunkjs.config({
            proxyPath: "/proxy",
            scheme: "https",
            host: "localhost",
            port: 8089,
            onSessionExpired: function(authenticate, done) {
                window.location.replace("login_form.html");
            },
            authenticate: function(done) {
                require([
                    "jquery",
                    "jquery.cookie"
                ], function($) {
                    // Retrieve the session key and current username from cookies
                    splunkSessionKey = $.cookie("splunk_sessionkey");
                    splunkCurrentUser = $.cookie("splunk_username");

                    // Log in using the session key and username
                    if (splunkSessionKey) {
                        done(null, {sessionKey: splunkSessionKey, username: splunkCurrentUser});
                    }
                    // If there is no session key, redirect to the login form
                    else {
                        window.location.replace("login_form.html");
                    }
                });
            }
        });

        // Set up the Web Framework components
        var deps = [
            "splunkjs/ready!",
            "splunkjs/mvc/searchmanager",
            "splunkjs/mvc/tableview",
            "jquery",
            "splunkjs/splunk"
        ];
        require(deps, function(mvc) {
            // Load individual components
            var SearchManager = require("splunkjs/mvc/searchmanager");
            var TableView = require("splunkjs/mvc/tableview");
            var $ = require("jquery");
            var jssdk = require("splunkjs/splunk");

            // Create a real-time search
            var search1 = new SearchManager({
                id: "search1",
                search: "index=_internal | head 5",
                earliest_time: "rt-30s",
                latest_time: "rt"
            });

            // Create a table
            var table1 = new TableView({
                id: "table1",
                managerid: "search1",
                el: $("#table1")
            });

            // When the Log Out button is clicked, end the session by deleting the session key
            // using the splunkjs.Service.Endpoint.del method of the Splunk SDK for JavaScript API
            // and the DELETE authentication/httpauth-tokens/{name} endpoint of the Splunk REST API
            $("#logout").on("click", function() {
                var http =  new jssdk.ProxyHttp("/proxy");
                var service = new jssdk.Service(http, {
                    sessionKey: splunkSessionKey,
                    scheme: "https",
                    host: "localhost",
                    port: 8089
                });
                service.del("/services/authentication/httpauth-tokens/" + splunkSessionKey);
                $.cookie("splunk_sessionkey", null);
            });
        });
    </script>
</body>
</html>

For more information