AngularJS显示403 http错误代码的自定义错误消息/页面

时间:2016-04-14 13:46:21

标签: java angularjs spring-security

在AngularJS网络应用程序中,如何显示403 http响应的自定义错误消息/页面。

我使用Spring安全性并检查用户是否具有适当的角色......如果他没有该角色,则应用程序返回http错误代码403.

目前我没有在这种情况下显示任何错误消息/页面。并希望实现这一点。我们怎么做到这一点?

Spring启动java代码

        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);

2 个答案:

答案 0 :(得分:2)

首先,您可以使用http拦截器拦截所有响应。

然后,如果您使用的是ui-router,您可以创建一个单独的未授权状态(使用apt视图和控制器)并在403上转换到该状态,如下所示

.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:我们不能在拦截器中注入$ state,因为它会导致循环依赖。所以使用$ injector。 有关此here

的更多信息

答案 1 :(得分:1)

您可以使用http拦截器过滤响应并显示自定义消息。这里有一个好的:https://github.com/witoldsz/angular-http-auth

相关问题