Announcement Announcement Module
Collapse
No announcement yet.
How do I create a custom JSON 401 page for my Spring MVC web service? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How do I create a custom JSON 401 page for my Spring MVC web service?

    I'm trying to create a secured restful web service using Spring MVC and Spring Security. I'd like to return som JSON message on a 401 instead of the default HTML message returned by Spring.

    I've tried several approaches but can't seem to get this working.

    My controller looks like follows:

    Code:
    @Controller
    @RequestMapping("/")
    public class ApplicationController {
    
        private ApplicationFactory applicationFactory;
    
        @Inject
        public ApplicationController(ApplicationFactory applicationFactory) {
            super();
            this.applicationFactory = applicationFactory;
        }
    
        @RequestMapping(method = GET)
        @ResponseBody
        @Secured("ROLE_USER")
        public Application getApplicationInfo() {
            return applicationFactory.buildApplication(this);
        }
    
    }
    And my Spring Security context looks as follows:

    Code:
      <security:global-method-security secured-annotations="enabled" mode="aspectj" />
    
      <security:http auto-config="true" use-expressions="true">
        <security:http-basic />
      </security:http>
    I've tried adding the following:

    Code:
        @ExceptionHandler(AccessDeniedException.class)
        @ResponseBody
        public Application accessDenied() {
            return applicationFactory.buildApplication(this);
        }
    But it gets ignored. I've tried adding "access-denied-page="/denied"" to my security:http tag with the following in my controller:

    Code:
        @RequestMapping(value = "/denied", method = GET)
        @ResponseBody
        public Application accessDenied() {
            return applicationFactory.buildApplication(this);
        }
    But it gets ignored. I've tried a custom access denied handler as follows:

    Code:
      <security:http auto-config="true" use-expressions="true">
        <security:http-basic />
        <security:access-denied-handler ref="jsonAccessDeniedHandler" />
      </security:http>
    The only thing that does seem to work is the following:

    Code:
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public Application accessDenied() {
            return applicationFactory.buildApplication(this);
        }
    But this catches everything and I only want to customise a failed authentication.

    Any advice would be gratefully received. TIA...

    -- Ricardo
Working...
X