0

In AngularJS web app, How to show a custom error message / page for 403 http response.

I use Spring security and check if a user has a appropriate roles..and if he does not have the role the application returns http error code 403.

At the moment I am not showing any error message / page in such case. And would like to implement this. How can we do this ?

Spring boot java code

        http.httpBasic()
                .and()
                .authorizeRequests()

                // Permit these resources
                .antMatchers("/login", "/4_security/login.html", "/bower_components/**",  "/4_security/*.js", "/")
                .permitAll()

                // URL based Authorization control
                .antMatchers("/1_reportingEntities/*.html").hasAnyAuthority(authorities)

                // All other requests needs authentication
                .anyRequest().authenticated()

                // Access denied page (403 error)
                .and().exceptionHandling().accessDeniedPage("/0_common/accessDenied.html")

                .and()
                // CSRF protection
                .csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
Jay
  • 9,189
  • 12
  • 56
  • 96

2 Answers2

2

First of all, you can use an http interceptor to intercept all the responses.

Then,if you are using ui-router, you can create a separate unauthorized state (with apt view and controller) and transition to that state on 403 as shown below

.factory('authHttpResponseInterceptor',['$q','$location','$injector',function($q,$location, $injector){
return {
    responseError: function(rejection) {

        if (rejection.status === 403) {
            console.error("Response 403 in interceptor");
            $injector.get('$state').go('unauthorised');
        }

        return $q.reject(rejection);
    }

PS : we can not inject $state in interceptor as it will result in circular dependency. So $injector is used. More on this here

Community
  • 1
  • 1
Maverick
  • 454
  • 2
  • 11
  • Thanks I am not using ui-router. – Jay Apr 14 '16 at 14:09
  • 1
    if you are using angular-route then you can use something like $location.path('/unauthorized') instead of $injector.get('$state').go('unauthorised'); – Maverick Apr 14 '16 at 14:19
1

You can use an http interceptor to filter responses and show your custom message. A good one is available here: https://github.com/witoldsz/angular-http-auth

Daniel Higueras
  • 2,404
  • 22
  • 34