How to show customised error page for forbidden url access in grails 3.3.9

435 Views Asked by At

My grails 3.3.9 application has different modules implemented with different ROLE based access using spring security.

AdminController accessed via ROLE_ADMIN. If a non-admin user logged in and try to access Admin URL then grails show

[Image]Grails Error Message: Sorry, you're not authorized to view this page.

I want to show my custom message.

[Image: ]Custom Message: 403 Access Forbidden

application.groovy

grails.plugin.springsecurity.interceptUrlMap = [
        [pattern: '/user/**', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/role/**', access: ['ROLE_ADMIN']],
        [pattern: '/', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/admin/*', access: ['ROLE_ADMIN']]]

URLMappings

"500"(controller: "error", action: "internalServerError")
"404"(controller: "error", action: "notFound")
"403" (controller: "error", action: "forbidden")
"403"(view: "/error/forbidden")

I have individually for 403.

500 & 404 is working correctly.

2

There are 2 best solutions below

3
erichelgeson On

In URlMappings you can set a mapping to the response code and choose a controller or view to respond with - eg:

static mappings = {
    // ... other mappings ...
    // Send 403's to a controller if you'd like to do additional logic
    "403"(controller: "errors", action: "forbidden")
    // Or just render a static view under grails-app/views/errors/forbidden.gsp
    "403"(view: "/errors/forbidden")
}

See: http://docs.grails.org/4.0.1/guide/single.html#mappingToResponseCodes

0
user1071671 On

You need to set following configuration in application.groovy as well.

grails.plugin.springsecurity.adh.errorPage = null //to throw 403 page on access denied