I have a pure java script application without servlet or any other backend framework. I have created a jsp file: keycloakClientHome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="js/keycloak.js"></script>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript" src="js/keycloak-call.js"></script>
</head>
<body>
<script>
parent.postMessage(location.href, location.origin)
</script>
<a href="#" id="keycloakCallId">Call Protected Agent</a>
<h1 id="results">Result:</h1>
</body>
</html>
keycloak-call.js /** * */
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');
});
});
});
When I hit from the browser http://localhost:8086/KeycloakJSClient/keycloakClientHome.jsp..gets redirected to keycloak login page and on successful login it shows the jsp content.
When I click the link and call the protected REST API, deployed on same server.
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.
The client Accesstype in keycloak is public
Keycloak.json file used in REST API and javscript application
{
"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
}