title: Keycloak javascript adapter to call protected rest api
body: <p>I have a pure java script application without servlet or any other backend framework.
  I have created a jsp file:
  keycloakClientHome.jsp</p>
  
  <pre><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%&gt;
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
  &lt;title&gt;Insert title here&lt;/title&gt;
  &lt;script type="text/javascript" src="js/keycloak.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="js/jquery-3.4.1.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="js/keycloak-call.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
   &lt;script&gt;
          parent.postMessage(location.href, location.origin)
   &lt;/script&gt;
   &lt;a href="#" id="keycloakCallId"&gt;Call Protected Agent&lt;/a&gt;
   &lt;h1 id="results"&gt;Result:&lt;/h1&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>keycloak-call.js
  /**
   * 
   */</p>
  
  <pre><code>     var keycloak = Keycloak();
      keycloak.init({
           onLoad: 'login-required',}).success(function(authenticated) {
          alert(authenticated ? 'authenticated' : 'not authenticated');
      }).error(function() {
          alert('failed to initialize');
      });
  
  $(document).ready(function(){
  
      $("#keycloakCallId").click(function(e){
          keycloak.updateToken(30).success(function() {
              //Call to protected rest API
              $.ajax({
                     type: "GET",
                     beforeSend: function(request) {
                         console.log("Token value"+keycloak.token);
                          request.setRequestHeader("Authorization", "Bearer "+keycloak.token);
                         /*request.setRequestHeader("Authentication", "Basic "+encodeBase64('rachel' + ":" + 'rachel'));*/
                        },
                     url: "http://localhost:8086/dbaasrest/login",
                     contentType: "json",
                     success: function(data) {
                         console.log("response:" + data);
                         $("#results").append(data);
                     },
                     error: function(jqXHR, textStatus, errorThrown) {
                         console.log(' Error in processing!');
  
                     }
                 });
          }).error(function() {
              alert('Failed to refresh token');
          });
  
       });
  });
  </code></pre>
  
  <p>When I hit from the browser <a href="http://localhost:8086/KeycloakJSClient/keycloakClientHome.jsp..gets" rel="nofollow noreferrer">http://localhost:8086/KeycloakJSClient/keycloakClientHome.jsp..gets</a> redirected to keycloak login page and on successful login it shows the jsp content.</p>
  
  <p><a href="https://i.stack.imgur.com/GV0Kw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GV0Kw.jpg" alt="Home jsp page "></a></p>
  
  <p>When I click the link and call the protected REST API, deployed on same server.
  <a href="https://i.stack.imgur.com/EcDgK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EcDgK.jpg" alt="error in browser console"></a></p>
  
  <p>When I hit the spring rest api, it do not ask for authentication anymore, since already authenticated.
  Javascript and spring rest api are two different applications both deployed on tomcat port-8086.
  But when I hit the link from authenticated jsp page and it shows 401-Unauthorized.Can anyone tell me, what might be the reason.</p>
  
  <p>The client Accesstype in keycloak is public</p>
  
  <p>Keycloak.json file used in REST API and javscript application</p>
  
  <pre><code>{
    "realm": "dev",
    "auth-server-url": "http://localhost:8080/auth",
    "ssl-required": "external",
    "resource": "employee-service",
    "public-client": true,
    "verify-token-audience": true,
    "use-resource-role-mappings": true,
    "confidential-port": 0,
    "enable-cors": true
  }
  </code></pre>
  
  <p>Keycloak Client settings screenshots
  <a href="https://i.stack.imgur.com/EqNEL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EqNEL.jpg" alt="Keycloak client setup"></a></p>
  
  <p><a href="https://i.stack.imgur.com/XMFan.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XMFan.jpg" alt="Client_role"></a></p>
  
  <p><a href="https://i.stack.imgur.com/XfmYH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XfmYH.jpg" alt="role and user mapping"></a></p>