Authenticating Nextcloud with Keycloak using OpenID Connect

A few months ago I started over on my home server with a fresh install of CentOS 7.6 (now updated to 7.7). I haven’t had a ton of time to work on it all at once, so I’ve been adding services one by one as I need them enough to make time for setup.

To get away from having a different login for every different thing I installed Keycloak was one of the first things I set up. Keycloak is an open source identity and access management tool that provides single-sign on with OpenID Connect and SAML. OpenID Connect was easy enough to set up with Jenkins and Gitea (using the appropriate plugins), but when I set up NextCloud I couldn’t find a tutorial (or any documentation really) for the plugin that offered OpenID Connect as an authentication mechanism. This post will document my path to getting a working OpenID Connect login added to my NextCloud instance.

Software Versions

Because I’m only working against a single configuration and don’t know how generally it will apply across other versions, here’s the list of the software I’m using for this post.

Getting Started

I’ll assume from here that all the above pieces are installed and configured for general use, just not hooked up together. From memory: Keycloak needs a realm set up with at least one user that will be set up for Nextcloud and Nextcloud needs the Social Login app installed and enabled on the Apps page.

Keycloak

Go to the Realm Settings page and open the “OpenID Endpoint Configuration” link in a new tab to bring up the .well-known/openid-configuration page. You’ll want the information from this page later to configure the Social Login plugin in Nextcloud.

Open the Clients page and click the create button. Select:

Client IDnextcloud
Client Protocolopenid-connect
Root URLhttps://<URL here>/nextcloud/

Click Save. On the next page (Settings) set:

Access Typeconfidential

Click Save, then click on the Roles tab. Add a new role named “admin”. Click Save, then go to the Mappers tab and add a protocol mapper as follows:

Namerole
Mapper TypeUser Client Role
Client IDnextcloud
Token Claim Namenextcloud-roles
Claim JSON TypeString

Click save, then add the admin role to a Keycloak user as appropriate so admin access is available through the Keycloak authentication. You can verify the mapping and user by going back to clients > nextcloud > Client Scopes > Evaluate, selecting the user, then viewing the Generated Access Token.

Go to the Credentials tab to find the client secret that will be needed in Nextcloud.

Nextcloud

As a Nextcloud administrator user, go to the Settings > Administration > Social login page.

My preferred settings for the first section with reasoning:

  • Disable auto create new users: unchecked to allow users to be created from Keycloak without needing a separate user created in Nextcloud
  • Allow users to connect social logins with their account: unchecked because no users were created on Nextcloud directly.
  • Prevent creating an account if the email address exists in another account: checked
  • Update user profile every login: checked so user changes on Keycloak propagate on next use
  • Do not prune not available user groups on login: unchecked to propagate Keycloak changes on next use
  • Automatically create groups if they do not exists: unchecked to keep Social login from adding groups with the “keycloak-” prefix. I would have this checked if group names didn’t have a prefix added.
  • Restrict login for users without mapped groups: unchecked because all of my Keycloak users currently have access to Nextcloud, even if they don’t have a specific group assigned.
  • Disable notify admins about new users: unchecked

Be sure to click Save: nothing will warn you if you leave the page without saving.

Add a “Custom OpenID Connect” entry (many of these entries will refer to entries in the .well-known/openid-configuration page you opened earlier in Keycloak):

Internal Namekeycloak
Title Keycloak (OIDC)
Authorize url<.well-known entry: authorization_endpoint>
Token url<.well-known entry: token_endpoint>
User info URL <.well-known entry: userinfo_endpoint>
Logout URL <.well-known entry: end_session_endpoint>
Client Idnextcloud
Client Secret<Secret from the Credentials tab in Keycloak>
Scopeopenid
Groups claimnextcloud-roles

If you want to redirect to a specific page (instead of having it load a blank page when it goes to the logout URL) add: ?redirect_uri=<encodedRedirectUri> to the end, where <encodedRedirectUri> is a URI-encoded path to the page to load after logout.

Any roles listed in “nextcloud-roles” will be prefixed by “keycloak-” when they are converted into group names. I suspect, but haven’t confirmed, that it’s from the internal name of the connector. I had to add mappings from each of my roles to the group intended, though in the mapping there isn’t a prefix added, so “admin” -> “admin” correctly assigned users to the admin group. This is why I disabled “Automatically create groups if they do not exist” in the Social login settings.

Again, scroll all the way to the bottom of the page and click Save. Be sure the popup by the banner tells you that the page has saved.

Now go to your Personal > Social login settings page and from the Social login connect > Available providers section click on the Keycloak (OIDC) button. This will either bring you to your keycloak login page or, if you’re already logged in, simply add an entry for keycloak to your user.

Debugging

The easiest way I found to test was to have one tab logged in to the Keycloak administrator pages, one tab logged into my Nextcloud admin account, and a private window that I could log in and out of as needed as I tweaked controls for both parts.

Here a couple of the problems I ran into and why they were showing up:

ProblemResolution
No login button next to
SSO & SAML logins
Social login buttons are added to the
Direct log in page
Error: No id_token was found. Scope was set incorrectly, resulting in the
wrong data being read by Nextcloud.

Conclusion

At this point I have everything functioning so I can either connect social login to my current accounts or create accounts on Keycloak and have them be created in Nextcloud when used to log in, as well as assigning the admin group based on user role from Keycloak.

I may soon configure the login page to automatically redirect to the Keycloak OIDC connector (set ‘social_login_auto_redirect’ => true setting in config.php), but for now I’ll accept an extra click or two to log in, at least until I’ve used it for long enough for all of my sessions to time out and be logged back in.

Rothenburg ob der Tauber

For Labor Day we took a trip over to Rothenburg ob der Tauber, a town in the Bavarian region of Germany that still has a medieval walled city at its center.

The gate defenses are still intact, with multiple layers of walls to pass through and large gates to close across the way. Here’s the west gate from the outside and one of the southern gates from the inside:

The city was considered to be the ideal German “Home Town” by the Nazis. It was damaged by bombing during World War II, but donations from all over the world helped to rebuild it after the war. On the inside of the walkway around the top of the wall are stones with names and locations of donors. Below are the steps up to the walkway at a gate on the northern side of the city (Klingentor) and the view of a couple of the towers on the east side (Galentor and Röderturm) from inside the walkway. Röderturm is on the inside of a gate that has a bridge over a dry moat, but we didn’t get a picture of that on this trip.

In the center of town is St.Jakobskirche, or St. James’s Church is in the middle of Rothenburg. We didn’t go in on this trip, but we got a good view of it from the wall walk at the end of our visit.

Many of the buildings we saw were of the traditional “Half-Timbered” construction, where large pieces of timber were joined together to make the frame, then the gaps were filled in with a non-structural material, leaving the timber frame exposed on the outside of the building.

There were a number of fountains in Rothenburg. This one is the herrnbrunnen, which has a crowned mermaid with two fish tails on top. The inscription on it marks it as being from 1595, and it’s where bakers who were found to be fraudulent were dunked as a punishment.

All over Germany we’ve seen window boxes full of flowers outside houses, or when the weather isn’t as nice rows of potted flowers just inside windows. We don’t usually stop to take pictures of them, but this one caught my eye as being an interesting pattern.

Himeji Castle

While we were in Japan last fall we stopped in Himeji to see Himeji Castle, also called “White Egret Castle” or “White Heron Castle” due to its distinctive white exterior.

A significant part of the white look is the mortar that covers the seams of the tiles on the roof. Keeping it bright white requires periodic restoration, and we were fortunate to visit just a few years after extensive work was completed in 2015. Still, there was work being done on buildings around the castle, so here’s a closeup of a just-completed section of roof.

The featured picture at the top of this post is the view of the castle from the street just outside the garden/park area in front of the castle. Here are a few other shots we got of the exterior as we made our way to and around the castle:

The main gate to the complex was large and led straight into a courtyard, but the next gate into a passage leading up the hill toward the castle was not built with tall people in mind. Or perhaps more accurately: it was built with defense against tall or mounted visitors in mind. There was another gate later on that didn’t even clear my shoulders, but that one was well padded to keep visitors from bumping their heads too hard.

From a distance you can see the caps on the bottom of each row of roof tiles, but once you get close you can see the details on them. Every single one was stamped with a pattern of some sort: these appear to just be decorative but one spot was labeled to say it was the family crest.

The inside furnishings were much more for defense and support of soldiers than for living quarters for nobles, which is how many surviving European castles tend to be designed. All the windows had platforms inside them for defenders to stand on, even the upper row on the taller floor at the bottom. Many of the walls were movable, so the space could be opened up or partitioned off, but in the solid walls there were lots of racks for weapons. There were also plenty of holes along the outer wall to drop things down on attackers below, especially in the corners under the eaves of the roof levels where the windows couldn’t see.

Once we were to the higher roof levels we could see just how big the fish that decorate the ends of the roof peaks are. Obviously there’s not much to get a sense of scale in the first picture of the fish with just the roof in the foreground, but the second picture is a full-size replica of the previous style of fish, and it reaches nearly to the ceiling inside the room in the museum section.

The view from the castle was also pretty impressive. It was built on a hill, so it started with a decent vantage, then it was tall enough to see over the city below it, even with modern buildings. The large road that’s centered in the picture links the train station to the castle complex.

We didn’t know it till we got to Japan, but Japanese cities often have cute little city mascots (apparently called yuru-chara). They especially show up on souvenirs and signs, and Himeji naturally chose a representation of the castle. We didn’t get a great picture of the castle mascot, but to the left is a cropped down piece of a sign.

Another unique thing about Japan that surprised us was that the manhole covers were often designs unique to the city and colored in for extra style. Below are the various ones we found in Himeji. The only place we saw the castle was just outside the train station, but the other designs here showed up frequently as we walked around.

After we finished in the castle we made our way back to the train station. This was the view down the street from there near sunset, looking above the various stoplights and street signs: