Announcement Announcement Module
Collapse
No announcement yet.
SecurityContextHolder Page Title Module
Move Remove Collapse
This topic is closed
X
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • SecurityContextHolder

    Hello everyone,

    i am playing around with Spring and Security at the moment and i ran into a problem i hope someone can help me out with.

    I set up the Contacts application and it works fine and i think i understand now whats going on most of the time.

    But then i wanted to add some usertracking just for testing but i am having problems reading the SecurityContextHolder


    I added the following to the contacts SecureIndexController:

    Code:
    		SecurityContext context = SecurityContextHolder.getContext();		
    		Authentication authentication = context.getAuthentication();
    		
    		
    		if(authentication == null){
    			System.out.println("Authentication was NULL");
    		} else {
    		        System.out.println("USER WAS "+authentication.getName());		
    		}
    But the Authentication Object is always NULL so i was wondering if i am missing something that i have to add to my xml file.

    Can anyone please put me in the right direction?
    I couldnt find anything about the Setup of the SecurityContextHolder so i thought it is set up automaticly by the login setup.

    THx in advance for any hint you guys can share

  • #2
    Where are you calling it from? If you call it from within the filter chain stack, with an authenticated user, it will not be null.

    Comment


    • #3
      Well i call it from inside a Page-Controller.

      Should i be able to access the Athentication Object from there?

      Comment


      • #4
        I don't know what a "Page-Controller" is, but if it is handling a request which has passed through the security filter chain, and the user is authenticated, then the Authentication object will be present.

        Comment


        • #5
          Well this is my code:

          Code:
          /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
           *
           * Licensed under the Apache License, Version 2.0 (the "License");
           * you may not use this file except in compliance with the License.
           * You may obtain a copy of the License at
           *
           *     http://www.apache.org/licenses/LICENSE-2.0
           *
           * Unless required by applicable law or agreed to in writing, software
           * distributed under the License is distributed on an "AS IS" BASIS,
           * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           * See the License for the specific language governing permissions and
           * limitations under the License.
           */
          
          package sample.contact;
          
          import org.springframework.beans.factory.InitializingBean;
          
          import org.springframework.security.Authentication;
          import org.springframework.security.context.SecurityContext;
          import org.springframework.security.context.SecurityContextHolder;
          import org.springframework.util.Assert;
          
          import org.springframework.web.servlet.ModelAndView;
          import org.springframework.web.servlet.mvc.Controller;
          
          import java.io.IOException;
          
          import java.util.HashMap;
          import java.util.List;
          import java.util.Map;
          
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          
          
          /**
           * Controller for secure index page.
           *
           * @author Ben Alex
           * @version $Id: SecureIndexController.java 1496 2006-05-23 13:38:33Z benalex $
           */
          public class SecureIndexController implements Controller, InitializingBean {
              //~ Instance fields ================================================================================================
          
              private ContactManager contactManager;
          
              //~ Methods ========================================================================================================
          
              public void afterPropertiesSet() throws Exception {
                  Assert.notNull(contactManager, "A ContactManager implementation is required");
              }
          
              public ContactManager getContactManager() {
                  return contactManager;
              }
          
              public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {    	
              	
              	
              	
          		SecurityContext context = SecurityContextHolder.getContext();
          		
          		Authentication context2 = context.getAuthentication();
          		
          		
          		if(context2 == null){
          			System.out.println("Authentication was NULL");
          		} else {
          		System.out.println("USER WAS "+context2.getName());
          		
          		}
          		
          		
                  List myContactsList = contactManager.getAll();
                  Contact[] myContacts;
          
                  if (myContactsList.size() == 0) {
                      myContacts = null;
                  } else {
                      myContacts = (Contact[]) myContactsList.toArray(new Contact[] {});
                  }
          
                  Map model = new HashMap();
                  model.put("contacts", myContacts);
          
                  return new ModelAndView("index", "model", model);
              }
          
              public void setContactManager(ContactManager contact) {
                  this.contactManager = contact;
              }
          }
          And the Auth Object is Null when ever the Site is called. Which should not be because the user hast to log in to get to the site
          Last edited by Rozik; Jul 6th, 2008, 06:11 AM.

          Comment


          • #6
            If I cut and paste your code into the SecureIndexController (current trunk code), browse to /secure/index.htm, log in as prompted (user "rod"), then I get:

            Code:
            [DEBUG,FilterChainProxy,btpool0-1] /secure/index.htm reached end of additional filter chain; proceeding with original chain
            USER WAS rod
            [DEBUG,AbstractFallbackMethodDefinitionSource,btpool0-1] Adding security method [CacheKey[sample.contact.ContactManagerBackend; public abstract java.util.List sample.contact.ContactManager.getAll()]] with attribute [[ROLE_USER, AFTER_ACL_COLLECTION_READ]]
            which is what I would expect.

            Comment


            • #7
              Thats really wierd.

              This is what i get:

              Code:
              [DEBUG,ContactManagerBackend,http-8080-2] Returning random contact
              [DEBUG,ContactManagerBackend,http-8080-2] Returning random contact
              [WARN,ResourceBundleMessageSource,http-8080-2] ResourceBundle [classpath:/org/acegisecurity/messages] not found for MessageSource: Can't find bundle for base name classpath:/org/acegisecurity/messages, locale de_DE
              [WARN,ResourceBundleMessageSource,http-8080-2] ResourceBundle [classpath:/org/acegisecurity/messages] not found for MessageSource: Can't find bundle for base name classpath:/org/acegisecurity/messages, locale de_DE
              [WARN,LoggerListener,http-8080-2] Authentication event AuthenticationSuccessEvent: marissa; details: org.acegisecurity.ui.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1F1EE435C71135F8A611660F838C20AF
              [WARN,LoggerListener,http-8080-2] Authentication event InteractiveAuthenticationSuccessEvent: marissa; details: org.acegisecurity.ui.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1F1EE435C71135F8A611660F838C20AF
              Authentication was NULL
              [DEBUG,ContactManagerBackend,http-8080-2] Returning all contacts
              [DEBUG,ContactManagerBackend,http-8080-2] Returning all contacts
              The rest of the application works just fine

              Comment


              • #8
                It looks like you are doing something different - the random contact is returned when browsing to the main (public) index, not the secure one. Please give a step-by-step complete description of what you do and what you observe and make sure debug logging is fully enabled so you can see how each request is handled.

                And look at the class names in the log:

                org.acegisecurity.ui.WebAuthenticationDetails is an Acegi Security class...

                but the code you have posted is from Spring Security. So something weird is going on.

                Comment


                • #9
                  Ok here is what i did:

                  I copied all the Files from the Contacts Sample in into Eclipse changed the Few lines above in the SecureIndexController to access the auth object.

                  then i did a run on server and get this in the log when i get to the main page

                  Code:
                  [DEBUG,ContactManagerBackend,http-8080-1] Returning random contact
                  [DEBUG,ContactManagerBackend,http-8080-1] Returning random contact
                  then i click on manage and get this message:

                  Code:
                  [WARN,ResourceBundleMessageSource,http-8080-1] ResourceBundle [classpath:/org/acegisecurity/messages] not found for MessageSource: Can't find bundle for base name classpath:/org/acegisecurity/messages, locale de_DE
                  and then i log in as bill wombat and get the following output:

                  Code:
                  [WARN,ResourceBundleMessageSource,http-8080-1] ResourceBundle [classpath:/org/acegisecurity/messages] not found for MessageSource: Can't find bundle for base name classpath:/org/acegisecurity/messages, locale de_DE
                  [WARN,LoggerListener,http-8080-1] Authentication event AuthenticationSuccessEvent: bill; details: org.acegisecurity.ui.WebAuthenticationDetails@43458: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: EB57CDC6958A09021C7DF70BBCBFFCFD
                  [WARN,LoggerListener,http-8080-1] Authentication event InteractiveAuthenticationSuccessEvent: bill; details: org.acegisecurity.ui.WebAuthenticationDetails@43458: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: EB57CDC6958A09021C7DF70BBCBFFCFD
                  Authentication was NULL
                  [DEBUG,ContactManagerBackend,http-8080-1] Returning all contacts
                  [DEBUG,ContactManagerBackend,http-8080-1] Returning all contacts
                  its really wierd i didnt do anthing else to the code or the programm but add those few lines the read the auth object

                  Comment


                  • #10
                    oh my :-)

                    Your hint that the code was spring security made me find the problem:-)

                    One othere thing i did was add the spring security jar :-)

                    so this was the problem:
                    Code:
                    import org.springframework.security.Authentication;
                    import org.springframework.security.context.SecurityContext;
                    import org.springframework.security.context.SecurityContextHolder;

                    changing it to acegi code makes it work
                    Code:
                    import org.acegisecurity.Authentication;
                    import org.acegisecurity.context.SecurityContext;
                    import org.acegisecurity.context.SecurityContextHolder;

                    thx a lot for your help :-)

                    and by the way its Sunday you should be out in the sun :-)

                    Comment


                    • #11
                      If you are starting out, I'd recommend you work with Spring Security rather than Acegi (which is now deprecated). But don't mix the two :-).

                      Comment


                      • #12
                        i was getting the same trouble.... null on SecurityContextHolder.getContext()

                        and i resolve it doing this:

                        private static String EMAIL_USUARIO_LOGADO = ((UserDetails) SecurityContextHolder.getContext().getAuthenticati on().getPrincipal()).getUsername();

                        and i think itīs probably thatīs wird behavior is because of class loaders working wrong

                        Comment

                        Working...
                        X