Package org.jboss.seam.security

Examples of org.jboss.seam.security.Identity


      assert request.isUserInRole(JAAS_ROLE);
   }
  
   public HttpServletRequest initializeWrappedRequest() {
      HttpSession session = new MockHttpSession();
      Identity identity = new Identity() {

         @Override
         public Principal getPrincipal()
         {
            return new SimplePrincipal(SEAM_USER);
View Full Code Here


         Lifecycle.beginCall();
        
         // Create a mock session
         Contexts.getSessionContext().set(Component.getComponentName(Session.class), new Session());
        
         Identity identity = new MockIdentity();
         identity.create();
        
         // Put the identity into our session context
         Contexts.getSessionContext().set(Component.getComponentName(Identity.class), identity);        
        
         // Test addRole()
         identity.addRole("admin");
        
         assert(!identity.hasRole("admin"));
        
         try
         {
            // This should throw a NotLoggedInException
            identity.checkRole("admin");
            assert(false);
         }
         catch (NotLoggedInException ex)
         {
            // expected
         }        
                 
         identity.getCredentials().setUsername("foo");
         identity.getCredentials().setPassword("bar");
        
         assert("foo".equals(identity.getCredentials().getUsername()));
         assert("bar".equals(identity.getCredentials().getPassword()));
        
         assert("loggedIn".equals(identity.login()));
         assert(identity.isLoggedIn());
        
         // Pre-authenticated roles are cleared before authenticating,
         // so this should still return false
         assert(!identity.hasRole("admin"));
        
         // The foo role is added by MockLoginModule
         assert(identity.hasRole("foo"));
        
         identity.removeRole("foo");
         assert(!identity.hasRole("foo"));
        
         try
         {
            // This should throw an AuthorizationException
            identity.checkRole("foo");
            assert(false);
         }
         catch (AuthorizationException ex)
         {
            // expected
         }
        
         // Now that we're authenticated, adding a role should have an immediate effect
         identity.addRole("admin");
         assert(identity.hasRole("admin"));
                 
         identity.logout();
        
         assert(!identity.hasRole("admin"));        
         assert(!identity.isLoggedIn());
      }
      finally
      {
         Lifecycle.endApplication();
      }
View Full Code Here

   @Test
   public void testDisableSecurity()
   {
      try
      {     
         Identity identity = new Identity();
         identity.create();
        
         // Disable security
         Identity.setSecurityEnabled(false);
        
         assert(!Identity.isSecurityEnabled());
         assert(identity.hasRole("admin"));
         assert(identity.hasPermission("foo", "bar"));
  
         // This shouldn't throw an exception while security is disabled
         identity.checkRestriction("foo");
        
         // Enable security
         Identity.setSecurityEnabled(true);
         assert(Identity.isSecurityEnabled());
         assert(!identity.hasRole("admin"));
         assert(!identity.hasPermission("foo", "bar"));
      }
      finally
      {
         Identity.setSecurityEnabled(true);
      }     
View Full Code Here

    public String getUsername(String id) {
        log.debug("trying to get username of Http session: " + id);
        HttpSession session = WikiServletListener.getSessions().get(id);
        String username = User.GUEST_USERNAME;
        if (session != null) {
            Identity identity = (Identity)session.getAttribute(SESSION_ATTR_IDENTITY);
            if (identity != null && identity.getPrincipal() != null)
                username = identity.getPrincipal().getName();
        }
        return username;
    }
View Full Code Here

   /**
    *  Synchronises the state of the security context with that of the subject
    */
   private void synchronizeContext()
   {
      Identity identity = Identity.instance();
     
      if (getSecurityContext() != null)
      {
         getSecurityContext().insert(identity.getPrincipal());
        
         for ( Group sg : identity.getSubject().getPrincipals(Group.class) )     
         {
            if ( Identity.ROLES_GROUP.equals( sg.getName() ) )
            {
               Enumeration e = sg.members();
               while (e.hasMoreElements())
               {
                  Principal role = (Principal) e.nextElement();
  
                  boolean found = false;
                  Iterator<Role> iter = getSecurityContext().iterateObjects(new ClassObjectFilter(Role.class));
                  while (iter.hasNext())
                  {
                     Role r = iter.next();
                     if (r.getName().equals(role.getName()))
                     {
                        found = true;
                        break;
                     }
                  }
                 
                  if (!found)
                  {
                     getSecurityContext().insert(new Role(role.getName()));
                  }
                 
               }
            }
         }   
        
         Iterator<Role> iter = getSecurityContext().iterateObjects(new ClassObjectFilter(Role.class));
         while (iter.hasNext())
         {
            Role r = iter.next();
            if (!identity.hasRole(r.getName()))
            {
               FactHandle fh = getSecurityContext().getFactHandle(r);
               getSecurityContext().retract(fh);
            }
         }
View Full Code Here

     
      // Otherwise if identity management is enabled, use it.
      IdentityManager identityManager = IdentityManager.instance();
      if (identityManager != null && identityManager.isEnabled())
      {
         Identity identity = Identity.instance();
        
         try
         {
            boolean success = identityManager.authenticate(username, identity.getCredentials().getPassword());
           
            if (success)
            {
               for (String role : identityManager.getImpliedRoles(username))
               {
                  identity.addRole(role);
               }
            }
           
            return success;
         }
View Full Code Here

        if (action == null) {
            action = "json";
        }

        // log in
        Identity ids = Identity.instance();
        ids.getCredentials().setUsername(usr);
        ids.getCredentials().setPassword(pwd);

        try {
            ids.authenticate();
        } catch (LoginException e) {
            throw new ServletException(new IllegalArgumentException("Unable to authenticate user."));
        }

        log.debug("Successful login");
View Full Code Here

   /**
    *  Synchronises the state of the security context with that of the subject
    */
   private void synchronizeContext()
   {
      Identity identity = Identity.instance();
     
      getSecurityContext().insert(identity.getPrincipal());
     
      if (getSecurityContext() != null)
      {
         for ( Group sg : identity.getSubject().getPrincipals(Group.class) )     
         {
            if ( Identity.ROLES_GROUP.equals( sg.getName() ) )
            {
               Enumeration e = sg.members();
               while (e.hasMoreElements())
               {
                  Principal role = (Principal) e.nextElement();
  
                  boolean found = false;
                  Iterator<Role> iter = getSecurityContext().iterateObjects(new ClassObjectFilter(Role.class));
                  while (iter.hasNext())
                  {
                     Role r = iter.next();
                     if (r.getName().equals(role.getName()))
                     {
                        found = true;
                        break;
                     }
                  }
                 
                  if (!found)
                  {
                     getSecurityContext().insert(new Role(role.getName()));
                  }
                 
               }
            }
         }   
        
         Iterator<Role> iter = getSecurityContext().iterateObjects(new ClassObjectFilter(Role.class));
         while (iter.hasNext())
         {
            Role r = iter.next();
            if (!identity.hasRole(r.getName()))
            {
               FactHandle fh = getSecurityContext().getFactHandle(r);
               getSecurityContext().retract(fh);
            }
         }
View Full Code Here

   private void processBasicAuth(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException
   {
      Context ctx = new SessionContext( new ServletRequestSessionMap(request) );
      Identity identity = (Identity) ctx.get(Identity.class);

      if (identity == null)
      {
         throw new ServletException("Identity not found - please ensure that the Identity component is created on startup.");
      }
     
      Credentials credentials = (Credentials) ctx.get(Credentials.class);
     
      boolean requireAuth = false;
     
      String header = request.getHeader("Authorization");
      if (header != null && header.startsWith("Basic "))
      {
         String base64Token = header.substring(6);
         String token = new String(Base64.decode(base64Token));

         String username = "";
         String password = "";
         int delim = token.indexOf(":");

         if (delim != -1)
         {
             username = token.substring(0, delim);
             password = token.substring(delim + 1);
         }

         // Only reauthenticate if username doesn't match Identity.username and user isn't authenticated
         if (!username.equals(credentials.getUsername()) || !identity.isLoggedIn())
         {
            try
            {
               credentials.setPassword(password);
               authenticate( request, username );
            }        
            catch (Exception ex)
            {
               log.warn("Error authenticating: " + ex.getMessage());
               requireAuth = true;
           
         }
      }
     
      if (!identity.isLoggedIn() && !credentials.isSet())
      {
         requireAuth = true;
      }
     
      try
      {
         if (!requireAuth)
         {
            chain.doFilter(request, response);
            return;
         }
      }
      catch (NotLoggedInException ex)
      {
         requireAuth = true;
      }
     
      if ((requireAuth && !identity.isLoggedIn()))
      {
         response.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
         response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");        
      }              
   }
View Full Code Here

   private void processDigestAuth(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException
   {
      Context ctx = new SessionContext( new ServletRequestSessionMap(request) );
      Identity identity = (Identity) ctx.get(Identity.class);
     
      if (identity == null)
      {
         throw new ServletException("Identity not found - please ensure that the Identity component is created on startup.");
      }     
     
      Credentials credentials = (Credentials) ctx.get(Credentials.class);
     
      boolean requireAuth = false;   
      boolean nonceExpired = false;
     
      String header = request.getHeader("Authorization");     
      if (header != null && header.startsWith("Digest "))
      {       
         String section212response = header.substring(7);

         String[] headerEntries = section212response.split(",");
         Map<String,String> headerMap = new HashMap<String,String>();
         for (String entry : headerEntries)
         {
            String[] vals = split(entry, "=");
            headerMap.put(vals[0].trim(), vals[1].replace("\"", "").trim());
         }
        

         DigestRequest digestRequest = new DigestRequest();
         digestRequest.setHttpMethod(request.getMethod());
         digestRequest.setSystemRealm(realm);
         digestRequest.setRealm(headerMap.get("realm"));        
         digestRequest.setKey(key);
         digestRequest.setNonce(headerMap.get("nonce"));
         digestRequest.setUri(headerMap.get("uri"));
         digestRequest.setClientDigest(headerMap.get("response"));
         digestRequest.setQop(headerMap.get("qop"));
         digestRequest.setNonceCount(headerMap.get("nc"));
         digestRequest.setClientNonce(headerMap.get("cnonce"));
                 
         try
         {
            digestRequest.validate();
            request.getSession().setAttribute(DigestRequest.DIGEST_REQUEST, digestRequest);
            authenticate( request, headerMap.get("username") );
         }
         catch (DigestValidationException ex)
         {
            log.warn(String.format("Digest validation failed, header [%s]: %s",
                     section212response, ex.getMessage()));
            requireAuth = true;
           
            if (ex.isNonceExpired()) nonceExpired = true;
         }           
         catch (Exception ex)
         {
            log.warn("Error authenticating: " + ex.getMessage());
            requireAuth = true;
         }
      }  

      if (!identity.isLoggedIn() && !credentials.isSet())
      {
         requireAuth = true;
      }
     
      try
      {
         if (!requireAuth)
         {
            chain.doFilter(request, response);
            return;
         }
      }
      catch (NotLoggedInException ex)
      {
         requireAuth = true;
      }
     
      if ((requireAuth && !identity.isLoggedIn()))
      {     
         long expiryTime = System.currentTimeMillis() + (nonceValiditySeconds * 1000);
        
         String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
         String nonceValue = expiryTime + ":" + signatureValue;
View Full Code Here

TOP

Related Classes of org.jboss.seam.security.Identity

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.