AngularJS为403 http错误代码显示自定义错误消息/页面
问题描述:
在AngularJS Web应用程序中,如何显示403 http响应的自定义错误消息/页面。AngularJS为403 http错误代码显示自定义错误消息/页面
我使用Spring的安全,并检查用户是否有一个合适的roles..and如果他没有我不显示任何错误信息的作用,应用程序返回HTTP错误代码403
此刻/在这种情况下页面。并希望执行此操作。我们应该怎么做 ?
春季启动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);
答
首先,你可以使用http拦截器截获所有的响应。
然后,如果使用的是UI的路由器,则可以创建一个单独的未授权的状态(用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,因为它会导致循环依赖。所以使用$注入器。 更多关于here
谢谢我没有使用ui-router。 – Jay
如果你正在使用角路由,那么你可以使用像$ location.path('/ unauthorized')而不是$ injector.get('$ state')。go('unauthorized'); – Maverick