[keycloak-user] Can't access REST service with valid keycloak token after secure with keycloak

Erik G. Haugen erik.g.haugen at gmail.com
Wed Sep 5 04:05:32 EDT 2018


I used the keycloak Java API to get a valid token then using this token to
try to access a rest service that has been secured with keycloak but get
404 error, Not Found.

Here is my java code to get the token from keycloak. This appears to work:

   AuthzClient authzClient = AuthzClient.create();
AccessTokenResponse response = authzClient.obtainAccessToken(user,
password);


I get a valid token in the response. I then try to use this token to
access the REST service secured with keycloak:

    String urlString =
"http://localhost:3333/appname-1.0.0-SNAPSHOT/project/0.1/device/return/all";

    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    String authString = "Bearer " + tokenStr;
    con.setRequestProperty("Authorization", authString);
    basicStatus = con.getResponseCode();

The basicStatus returns 404

I secured the war file with the REST service by adding a web.xml file and a
keycloak.json file. If I remove the web.xml and keycloak.json file from the
war, then above code returns 200. But then the service is not secure.


web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
	
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Device</web-resource-name>
            <url-pattern>/device/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>device</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>KEYCLOAK</auth-method>
        <realm-name>this is ignored currently</realm-name>
    </login-config>

    <security-role>
        <role-name>device</role-name>
    </security-role>

</web-app>

user has role of device in keycloak.

Any idea what might be wrong?


More information about the keycloak-user mailing list