【问题标题】:AngularJS show custom error message / page for 403 http error codeAngularJS显示403 http错误代码的自定义错误消息/页面
【发布时间】:2016-08-06 02:59:52
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java angularjs spring-security


    【解决方案1】:

    首先,你可以使用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

    【讨论】:

    • 谢谢我没有使用 ui-router。
    • 如果你使用 angular-route 那么你可以使用类似 $location.path('/unauthorized') 而不是 $injector.get('$state').go('unauthorized') ;
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2020-01-21
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      相关资源
      最近更新 更多