Developer's Diary
Software development, with Terry Ebdon
13-Jun-2020 Grails Secured

Spring works

Following on from my failed attempts with role based authorisation I spent some time studying the plugin's documentation. It's well written and I'm really starting to like what Spring Security can do. It didn't highlight anything wrong with my approach though. I then created a test app, with minimal functionality. It behaved exactly the same as my prototype, i.e. logout doesn't work and BootStrap.groovy can't see any assigned roles. Back to the manual.

Log off

The correct way to log out is via /logoff. The link to a logoutController is a red herring.

The GSP has it

I found some interesting GSP tags for getting the current user and changing behaviour based on the assigned roles. I plugged those into the grails-app\views\lineUp\index.gsp and gave it a bash:

<sec:ifLoggedIn>
<hr/>
** Logged in as <sec:username/> **
</sec:ifLoggedIn>
<hr/>
<sec:access expression="hasRole('ROLE_ADMIN')">
<div>You&apos;re an admin</div>
</sec:access>
<sec:access expression="hasRole('ROLE_COACH')">
<div>You&apos;re a coach</div>
</sec:access>
<sec:access expression="hasRole('ROLE_ATHLETE')">
<div>You&apos;re an athlete</div>
</sec:access>

It works! The roles are correctly assigned and the page text changes depending on the user.

It looks like there are limits on the BootStrap behaviour. This doesn't seem to be documented, so may not be intentional. At this point I'm just glad to have got it working.

Page protection

This was easy. I added a static rule. in application.groovy, allowing only users with ROLE_ADMIN or ROLE_COACH to access the list of line-ups.

[pattern: '/lineUp/index', access: ["hasAnyRole('ROLE_ADMIN','ROLE_COACH')"]],
[pattern: '/**',           access: ['isAuthenticated()']]

12-JUN-2020 👈 Top of page 👉 15-JUN-2020

© 2020 Terry Ebdon.

Find me coding on GitHub, networking on LinkedIn, answering questions on Stack Exchange and hanging out on twitter.