Announcement Announcement Module
Collapse
No announcement yet.
SecurityContextHolder.getContext().getAuthenticati on() is null in 404 error page Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • SecurityContextHolder.getContext().getAuthenticati on() is null in 404 error page

    I want to show user(log-in) info on the top of 404 error page.

    I found that SecurityContextHolder.getContext().getAuthenticati on() is null in 404 error page if I use spring-security tag library.

    My configuration files is as follow.
    ============================================ 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/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="myApp" version="2.5">

    <display-name>myApp</display-name>
    <description>
    myApp Server
    </description>

    <!-- configure context parameters -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/conf/spring/context/*Context.xml
    </param-value>
    </context-param>
    <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/conf/log4j.xml</param-value>
    </context-param>
    <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>myApp.root</param-value>
    </context-param>

    <!-- configure filters -->
    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFil terProxy</filter-class>
    </filter>
    <filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEnco dingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>

    <!-- filter mapping -->
    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>*.do</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>*.json</url-pattern>
    </filter-mapping>

    <!-- configure listener -->
    <listener>
    <listener-class>org.springframework.web.util.Log4jConfigList ener</listener-class>
    </listener>
    <!-- RequestContextListener for Spring Security Locale -->
    <listener>
    <listener-class>org.springframework.web.context.request.Requ estContextListener</listener-class>
    </listener>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoade rListener</listener-class>
    </listener>

    <!-- configure servlet -->
    <servlet>
    <servlet-name>myApp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherSe rvlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/conf/spring/web/*Context.xml
    </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- configure servlet-mappings -->
    <servlet-mapping>
    <servlet-name>myApp</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>myApp</servlet-name>
    <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <!-- configure session -->
    <session-config>
    <session-timeout>10</session-timeout>
    </session-config>

    <!-- configure welcome-file -->
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <error-page>
    <error-code>404</error-code>
    <location>/errors/404.jsp</location>
    </error-page>

    </web-app>
    ================================================== ============================================


    ================================ the header of 404 error page ================================
    <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
    <div id="header">
    <!-- login info & language -->
    <div class="headerWrapper">
    <div class="headerLogo">
    <a href="<c:url value='/main.do'/>"><img src="<c:url value='/images/logo2.png'/>" /></a>
    </div>
    <div class="loginInfo">
    <div>
    <div class="language">
    <span><a class="changeLocale" href="javascript:changeLocale('fr');"><spring:mess age code='French' /></a></span>
    |
    <span><a class="changeLocale" href="javascript:changeLocale('en');"><spring:mess age code='English' /></a></span>
    </div>
    </div>
    <div>
    <div class="myInfo">
    <a href="<c:url value='/myinfo/main.do'/>"><img src="<c:url value='/images/log_icon.jpg'/>"/><sec:authentication property="principal.username"/></a>
    </div>
    <div class="logout">
    <input type="button" value="<spring:message code='Sign out' htmlEscape='true'/>" title="<spring:message code='Sign out' />" onClick="location.href='<c:url value='/j_spring_security_logout'/>';" />
    </div>
    </div>
    </div>
    </div>
    <!--// login info & language -->
    </div>
    ================================================== ============================================

    spring tag <sec:authentication property="principal.username"/> above is null.

    So, I make util class(AuthenticationUtils.java) for this case.

    AuthenticationUtils is working well. But I want to use spring tag library.

    Do anybody have good solution for this case?

    Thank you in advance ( I use springframework 3.0.4, spring-security 3.0.3)


    ================================== AuthenticationUtils.java ==================================
    public class AuthenticationUtils {
    public static Object getPrincipal() {
    Authentication auth = SecurityContextHolder.getContext().getAuthenticati on();
    if (auth == null) { // null if page 404 error
    auth = getAuthenticationFromSessionSecurityContext();
    System.out.println(SecurityContextHolder.getContex tHolderStrategy().getContext().getAuthentication() );
    }

    return auth.getPrincipal();
    }

    private static Authentication getAuthenticationFromSessionSecurityContext() {
    RequestAttributes attrs = RequestContextHolder.currentRequestAttributes();
    SecurityContext ctx = (SecurityContext) attrs.getAttribute(HttpSessionSecurityContextRepos itory.SPRING_SECURITY_CONTEXT_KEY, RequestAttributes.SCOPE_SESSION);

    return (Authentication) ctx.getAuthentication();
    }

    ================================================== ============================================

  • #2
    What does your Spring Security configuration look like (please use the code tags to make it easier to read)? One thing that could be wrong is that you might be skipping the url that is missing. Ensure that you have an intercept-url pattern for the resource that does not specify filters="none".

    Comment


    • #3
      My Security-config.xml is..

      my security-config.xml is as follow.

      404 error page is defined in web.xml.

      =============== security-config.xml ===============

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schem...-beans-3.0.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

      <!-- ===== HTTP CONFIG ===== -->
      <sec:http auto-config="true" access-denied-page="/accessDenied.do">
      <sec:intercept-url pattern="/charts/**" filters="none" />
      <sec:intercept-url pattern="/css/**" filters="none" />
      <sec:intercept-url pattern="/images/**" filters="none" />
      <sec:intercept-url pattern="/js/**" filters="none" />
      <sec:intercept-url pattern="/login.do*" filters="none" />
      <sec:intercept-url pattern="/myinfo/**" access="ROLE_ADMIN, ROLE_USER" />
      <sec:intercept-url pattern="/user/**" access="ROLE_ADMIN, ROLE_USER" />
      <sec:intercept-url pattern="/main.do*" access="ROLE_ADMIN, ROLE_USER" />
      <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_REMEMBERED" />
      <sec:form-login login-page="/login.do" default-target-url="/main.do" authentication-failure-url="/login.do" always-use-default-target="true" />
      <sec:logout logout-success-url="/index.html" />
      </sec:http>

      <sec:authentication-manager alias="authenticationManager">
      <sec:authentication-provider user-service-ref="adminManager">
      <secassword-encoder ref="passwordEncoder" />
      </sec:authentication-provider>
      </sec:authentication-manager>

      <!-- ===== User Detail Service : serviceContext.xml >> adminManager ===== -->

      <!-- ===== Md5PasswordEncoder ===== -->
      <bean id="passwordEncoder" class="org.springframework.security.authentication .encoding.Md5PasswordEncoder" />

      </beans>

      =============================================

      So, I replace /errors/404.jsp ==> /errors/404.do in web.xml

      ======== web.xml =======
      <error-page>
      <error-code>404</error-code>
      <location>/errors/404.do</location>
      </error-page>
      ======================

      and then i insert sentence below in Spring-config.xml


      === springContext.xml ===
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schem...-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schem...ontext-3.0.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

      <context:annotation-config/>
      <mvc:annotation-driven />
      <mvc:view-controller path="/errors/404.do" view-name="/errors/404" />

      </beans>
      ======================

      But, spring security tag doesn't work as my wish.
      Last edited by [email protected]; Oct 25th, 2010, 11:39 PM.

      Comment

      Working...
      X