“拒绝访问”页面重定向不起作用

问题描述 投票:0回答:3
  1. 我的Web项目基于Spring 3.2.5.RELEASE、JSF 2和PrimeFaces 6。我在服务层的类级别使用

    @PreAuthorize
    注释,如下所示:

    @Service("packageService")
    @Transactional(readOnly = true)
    @PreAuthorize("hasAnyRole('befit')")
    public class PackageServiceImpl implements PackageService {
    }
    
  2. 在 JSF 托管 bean 级别,我没有任何

    @PreAuthorize
    。在
    @PostConstruct
    方法上,我从服务层调用了几个需要授权的方法。

  3. 在XHTML页面,我使用EL从托管bean获取数据。

  4. 安全配置为:

    <sec:http auto-config="true" use-expressions="true">
    
            <sec:access-denied-handler error-page="/access.xhtml"/>
    
            <!-- Page level Spring Security : Intercept access to resources in /faces/** -->
            <sec:intercept-url pattern="/faces/admin/*"
                access="hasAnyRole('befit','admin')" />
    
            <sec:intercept-url pattern="/faces/befit/*"
                access="hasAnyRole('befit')" />
    
            <sec:intercept-url pattern="/faces/online/*"
                access="isAuthenticated()" />   
    
  5. 功能运行良好。如果用户登录“较少”角色并尝试访问需要“更多”角色的页面,我确实会从

    @PostConstruct
    方法中看到“访问被拒绝”异常。但它不会导航到
    access.xhtml
    页面。

注意:我尝试使用 bean 来处理

AccessDeniedException
作为

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + accessDeniedUrl));
    request.getSession().setAttribute("message", "You are not authorized to access this resource.");
}

我得到了如下的异常

响应提交 servlet 后无法调用 sendredirect

你能告诉我我想念什么吗?

注意:使用 StackTrace 进行更新

Oct 12, 2016 4:50:00 PM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/faces/befit/corporate/corporate_manage.xhtml]
com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean corporateManageMBean
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:227)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:161)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at javax.faces.component.UIInput.getValue(UIInput.java:291)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:94)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:58)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeMarkup(InputTextRenderer.java:71)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeEnd(InputTextRenderer.java:52)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    at com.itservicesdepot.befit.master.service.impl.CorporateServiceImpl$$EnhancerByCGLIB$$64cca414.fetchAll(<generated>)
    at com.itservicesdepot.befit.master.controller.managedBean.CorporateManageMBean.init(CorporateManageMBean.java:62)
    ... 90 more

Oct 12, 2016 4:50:00 PM com.sun.faces.context.ExceptionHandlerImpl throwIt
INFO: Exception when handling error trying to reset the response.
com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean corporateManageMBean
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:227)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:161)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at javax.faces.component.UIInput.getValue(UIInput.java:291)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:94)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:58)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeMarkup(InputTextRenderer.java:71)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeEnd(InputTextRenderer.java:52)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.sun.faces.spi.InjectionProviderException
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:115)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:95)
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
    ... 83 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:113)
    ... 85 more
Caused by: org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:60)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    at com.itservicesdepot.befit.master.service.impl.CorporateServiceImpl$$EnhancerByCGLIB$$64cca414.fetchAll(<generated>)
    at com.itservicesdepot.befit.master.controller.managedBean.CorporateManageMBean.init(CorporateManageMBean.java:62)
    ... 90 more

使用 Spring Security 进行更新

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd">

        <!-- Enable method level Spring Security by annotations -->
        <sec:global-method-security pre-post-annotations="enabled" />
        <sec:http auto-config="true" use-expressions="true">

            <sec:access-denied-handler ref="accessDeniedHandler"/>

            <!-- Page level Spring Security : Intercept access to resources in /faces/** -->
            <sec:intercept-url pattern="/faces/editor/*"
                access="hasAnyRole('editor,befit,admin')" />

            <sec:intercept-url pattern="/faces/admin/*"
                access="hasAnyRole('befit,admin')" />

            <sec:intercept-url pattern="/faces/befit/*"
                access="hasAnyRole('befit')" />

            <sec:intercept-url pattern="/faces/online/*"
                access="isAuthenticated()" />

            <!-- Page level Spring Security : Intercept access to resources in /WEB-INF/templates/** -->
            <sec:intercept-url pattern="/WEB-INF/templates/**"
                access="permitAll" />

            <!-- Page level Spring Security : Enable Primefaces -->
            <sec:intercept-url pattern="/javax.faces.resource/**"
                access="permitAll" />

            <!-- Define login page for Spring Security -->
            <sec:form-login login-page="/login.xhtml" />

            <!-- Define logout properties for Spring Security -->
            <sec:logout invalidate-session="true" delete-cookies="true"
                logout-success-url="/landing.xhtml"></sec:logout>
        </sec:http>

        <!-- Set customUserDetailsService class as the authentication Manager for 
            Spring Security -->
        <sec:authentication-manager alias="authenticationManager">
            <sec:authentication-provider
                user-service-ref="authenticationServiceImpl">
                <sec:password-encoder hash="plaintext"></sec:password-encoder>
            </sec:authentication-provider>
        </sec:authentication-manager>

        <!-- Inject authentication Manager to masterSecurityBean -->
        <bean id="loginMBean" name="loginMBean" class="com.itservicesdepot.befit.master.controller.managedBean.LoginMBean" scope="request">
            <property name="authenticationManager" ref="authenticationManager"></property>
        </bean>

        <bean id="accessDeniedHandler" class="com.itservicesdepot.befit.master.controller.validator.MasterAccessDeniedHandler">
            <property name="errorPage" value="/access.xhtml" />
         </bean>
</beans>

public class MasterAccessDeniedHandler extends org.springframework.security.web.access.AccessDeniedHandlerImpl {
    private final Logger logger = LoggerFactory.getLogger(MasterAccessDeniedHandler.class);



 @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        this.logger.info("redirect ");
       super.handle(request, response, accessDeniedException);
    }
}

使用 CorporateManageMBean 更新

    @PostConstruct
        public void init() {
            String id = this.getParameterByName(AppConstant.ID);

            if (StringUtils.isNotEmpty(id)) {
                this.corporate = this.corporateService.fetchById(Long.valueOf(id));
                this.header = this.getResourceByName("corporate.profile.label.modify.header");
            }
            else {
                this.corporate = new CorporateEntity();
                header = this.getResourceByName("corporate.profile.label.add.header");
            }

// this call to corporateService will throw AccessDenied
            this.corporates = this.corporateService.fetchAll();
            this.packages = this.packageService.fetchAll();

企业服务如下

@Service("corporateService")
@Transactional(readOnly = true)
@PreAuthorize("hasAnyRole('befit')")
public class CorporateServiceImpl implements CorporateService {

@Override
    public List<CorporateEntity> fetchAll() {
        return this.corporateDAO.fetchAll();
    }
}

已更新 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <welcome-file-list>
        <welcome-file>landing.xhtml</welcome-file>
    </welcome-file-list>

    <!-- All parameters -->
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>ultima-indigo</param-value>
    </context-param>
    <context-param>
        <param-name>primefaces.FONT_AWESOME</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <context-param>
        <param-name>facelets.DEVELOPMENT</param-name>
        <param-value>true</param-value>
    </context-param>

    <!-- All defined Listeners -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- All defined Servlets -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/root-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <!-- Mapping -->
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>
spring jsf spring-security
3个回答
0
投票
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Auth/Login";  //in your case /Account/Login
    options.LogoutPath = "/Auth/logout";
    options.AccessDeniedPath = "/Auth/AccessDenied";
});

-1
投票

如果我没记错的话,你必须使用“ROLE_”前缀和大写字符来代表你的角色。

  • 如果您只想授予对一个角色的访问权限,请使用 hasRole('ROLE_BEFIT').
  • 如果您想授予多个访问权限,请使用 hasAnyRole('ROLE_BEFIT', 'ROLE_ADMIN').

查看 Spring Security 手册,常见内置表达式部分。


-2
投票

从 Spring Security 配置中注释掉

<sec:access-denied-handler/>
并添加以下控制器建议来处理
AcessDeniedException
,然后重定向到访问拒绝页面。

@Component 
@ControllerAdvice 
public class ControllerBase { 

    @ExceptionHandler(value = AccessDeniedException.class) 
    public ModelAndView accessDenied() { 
        return new ModelAndView("redirect:access.xhtml"); 
    }
}

在你的配置文件中为你的

AccessDeniedHandler
声明一个bean,如下所示:

<http>
    <access-denied-handler ref="accessDeniedHandler"/>
</http>

<beans:bean id="accessDeniedHandler" class="com.ia.security.AccessDeniedHandlerImpl">
    <beans:property name="errorPage" value="/access.xhtml"/>
</beans:bean>

然后用你的

AccessDeniedHandler
做类似的事情:

public class AccessDeniedHandlerImpl extends org.springframework.security.web.access.AccessDeniedHandlerImpl {
    // SLF4J logger
    private static final Logger logger = LoggerFactory.getLogger(AccessDeniedHandlerImpl.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        logger.log("AccessDeniedException triggered!");
        super.handle(request, response, accessDeniedException);
    }
}

你在这里犯了一个基本错误。

使用 XML 中的 Access Denied Handler 重定向到 Access Denied Page 或从 AccessDeniedException 处理程序重定向。请勿同时使用。

删除您的 AccessDeniedException 处理程序,然后尝试。

访问拒绝处理程序已从 XML 完成重定向,您再次尝试重定向,但这是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.