Spring SecurityContext returning null authentication on error pages

前端 未结 2 1656
庸人自扰
庸人自扰 2021-01-18 04:18

I am trying to write a custom error page for errors like 403 (access denied) and 500 (internal server error). They would be rendered from Velocity template and have all mess

相关标签:
2条回答
  • 2021-01-18 04:58

    The problem may be that springSecurityFilterChain is not intercepting ERRORS. Try changing your mapping in web.xml to be

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    
    0 讨论(0)
  • 2021-01-18 05:18

    The problem you're running into is that the ExceptionTranslationFilter which translates exceptions into error pages comes before the SecurityContextPersistenceFilter which pulls the authentication out of the SecurityContextRepository and puts it into the SecurityContextHolder. When the request finishes the SecurityContextPersistenceFilter takes the information back out of the SecurityContextHolder.

    The reason it clears the SecurityContextHolder is that the SecurityContextHolder is typically thread local and if the servlet container were to reuse a thread (most do this) they might accidentally give those credentials to someone else.

    Typically the ExceptionTranslationFilter is the outermost filter to avoid the risk of any exceptions not getting translated.

    Your best bet is to probably write a custom ExceptionTranslationFilter which takes in the SecurityContextRepository (often the HTTP session as you mentioned) and provides access to the Authentication via the SecurityContextRepository and not the SecurityContextHolder. Keep in mind that the Authentication will still be null if the user isn't logged in.

    0 讨论(0)
提交回复
热议问题