Spring security Accessdeniedhandler not be called

Source: Internet
Author: User

1. Questions

When using spring security, Accecc-denied-handler is configured in Applicationcontext-security.xml:

<!--automatic configuration mode, intercept all requests, Role_user can be  -->

and the Accessdecisionmanager module clearly throws Accessdeniedexception:

public class Myaccessdecisionmanager implements Accessdecisionmanager {/** * @author LIGH4 March 31, 2015 5:28:21            */@Override public void Decide (authentication arg0, Object arg1, collection<configattribute> arg2)        Throws Accessdeniedexception {if (arg2 = = null) {return; } loghelper.debug (this, arg1.tostring ());        Object is a URL.        iterator<configattribute> ite = Arg2.iterator ();            while (Ite.hasnext ()) {Configattribute CA = Ite.next ();            String Needrole = ((securityconfig) CA). getattribute (); For (grantedauthority ga:arg0.getAuthorities ()) {if (Needrole.equals (Ga.getauthority ())) {//ga is user '                    s role.                Return }}}<strong><span style= "color: #FF0000;"        > Loghelper.warn (This, "No right of URL:" + arg1.tostring ()); throw new Accessdeniedexception ("No Right"); </span></strong>/** * @author ligh4 March 31, 2015 PM 5:28:21 */@Override public boolean supports (Configattribute AR    G0) {//TODO auto-generated method stub return true;        }/** * @author LIGH4 March 31, 2015 PM 5:28:21 * * @Override public Boolean supports (class<?> arg0) {    TODO auto-generated Method stub return true; }}
However, the exception cannot be caught in Myauthenticationfailurehandler:

/** * Class Myauthenticationfailurehandler Implementation Description: TODO class Implementation Description * * @author LIGH4 March 31, 2015 PM 4:04:40 */public Class Myauthentica    Tionfailurehandler implements Accessdeniedhandler {/** * @author LIGH4 March 31, 2015 afternoon 4:15:59 * * @Override public void handle (HttpServletRequest arg0, HttpServletResponse arg1, Accessdeniedexception arg2) throws Ioexce        Ption, servletexception {loghelper.debug (this, "handler accessdeniedexception ...");        HttpServletRequest HttpRequest = arg0;        is Ajax request? if ("XMLHttpRequest". Equals (Httprequest.getheader ("X-requested-with"))) {String msg = "{\" success\ ": false, \            "message\": \ "authentication-failure\"} ";            Arg1.setcontenttype ("JSON");            OutputStream outputstream = Arg1.getoutputstream ();            Outputstream.write (Msg.getbytes ());        Outputstream.flush (); }    }}

2. Causes

Reference: http://stackoverflow.com/questions/7013197/spring-3-security-accessdeniedhandler-is-not-being-invoked

The original content is as follows:

AccessDeniedHandlerIs invoked when user was logged in and there are no permissions to resource (source here). If you want to handle the request for login page when user was not loggedin, just configure insecurity-context:

<http ... entry-point-ref="customAuthenticationEntryPoint">

and define Customauthenticationentrypoint:

<beans:bean id="customAuthenticationEntryPoint" class="pl.wsiadamy.webapp.controller.util.CustomAuthenticationEntryPoint"></beans:bean>

TIP, don ' t try to ExceptionTranslationFilter fight with. I have tried to override org.springframework.security.web.access.ExceptionTranslationFilter , without effects:

<Beans:Bean ID="Exceptiontranslationfilter" class="Org.springframework.security.web.access.ExceptionTranslationFilter">  <Beans:Property Name="Authenticationentrypoint"ref="Customauthenticationentrypoint"/>  <Beans:Property Name="Accessdeniedhandler"ref="Accessdeniedhandler"/></Beans:Bean><Beans:Bean ID="Accessdeniedhandler" class="Org.springframework.security.web.access.AccessDeniedHandlerImpl">  <Beans:Property Name="ErrorPage"value="/accessdenied.htm"/></Beans:Bean>

The ref="customAuthenticationEntryPoint" just didn ' t invoked.


That is, only the actual access failure will enter the Accessdeniedhandler, if it is not logged or session timeout, and so on, will not trigger Accessdeniedhandler, but will jump directly to the landing page. Refer to ExceptionTranslationFilter the processing in the specific:

Dofilter function:

<span style= "color: #000000;" >public void DoFilter (ServletRequest req, servletresponse Res, Filterchain chain) throws IOException, Servle        texception {httpservletrequest request = (httpservletrequest) req;        HttpServletResponse response = (httpservletresponse) res;            try {chain.dofilter (request, response);        Logger.debug ("Chain processed normally");        } catch (IOException ex) {throw ex; } catch (Exception ex) {//Try to extract a springsecurityexception from the StackTrace Thro            wable[] Causechain = Throwableanalyzer.determinecausechain (ex); RuntimeException ase = (authenticationexception) throwableanalyzer.getfirstthrowableoftype (Authenticati            Onexception.class, Causechain); if (ase = = null) {ase = (accessdeniedexception) throwableanalyzer.getfirstthrowableoftype (accessdeniedexcep            Tion.class, Causechain);     }       if (ase! = null) {<strong><span style= "color: #FF0000;"                >handlespringsecurityexception (Request, response, chain, ASE);</span></strong>} else {                    Rethrow servletexceptions and Runtimeexceptions As-is if (ex instanceof servletexception) {                Throw (Servletexception) ex;                } else if (ex instanceof RuntimeException) {throw (runtimeexception) ex; }//Wrap other Exceptions.                This shouldn ' t actually happen//as we ' ve already covered all the possibilities for DoFilter            throw new RuntimeException (ex); }}}</span>

Handlespringsecurityexception function:

<span style= "color: #000000;" >private void Handlespringsecurityexception (HttpServletRequest request, httpservletresponse response, FilterChain Chain, RuntimeException exception) throws IOException, Servletexception {if (Exception instanceof authe nticationexception) {logger.debug ("authentication exception occurred;            Redirecting to authentication entry point ", exception);        Sendstartauthentication (Request, Response, chain, (authenticationexception) exception); } else if (Exception instanceof accessdeniedexception) {<strong><span style= "color: #FF0000;" >if (Authenticationtrustresolver.isanonymous (Securitycontextholder.getcontext (). GetAuthentication ())) </ span></strong> {logger.debug ("Access is denied (user is anonymous);                Redirecting to authentication entry point ", exception); <strong><span style= "color: #FF0000;" >sendstartauthentication (request, response, chain, new Insufficientauthenticationexception ("Full authentication is R equired to access this resource "));</span></strong>} else {Logger.debug ("Access is denied (user is not anonymous);                Delegating to Accessdeniedhandler ", exception);            Accessdeniedhandler.handle (Request, Response, (accessdeniedexception) exception); }}}</span>

Instead of calling Accessdeniedhandler, it is transferred to the verification page (that is, the landing page).

Therefore, it is necessary to pay attention to distinguish between login failure and no access to the situation.


Spring security Accessdeniedhandler not be called

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.