Example usage for java.security Principal Principal

List of usage examples for java.security Principal Principal

Introduction

In this page you can find the example usage for java.security Principal Principal.

Prototype

Principal

Source Link

Usage

From source file:org.duracloud.duradmin.spaces.controller.SnapshotControllerTest.java

protected void setupUserDetails() {
    EasyMock.expect(request.getUserPrincipal()).andReturn(new Principal() {
        @Override/*from w  w  w .  ja va2 s.c om*/
        public String getName() {
            return username;
        }
    });
    SecurityUserBean userBean = new SecurityUserBean(username, "password", userEmail, "", true, true, true,
            true, null, null);
    EasyMock.expect(userDetailsService.getUserByUsername(username)).andReturn(userBean);
}

From source file:com.surevine.alfresco.audit.integration.AbstractAuditIntegrationTestBase.java

protected void initialiseFixtures() {
    mockRequest = new MockHttpServletRequest();
    mockResponse = new MockHttpServletResponse();
    mockChain = new MockFilterChain();

    mockRequest.setMethod(cut.getMethod());

    // Set reasonable defaults.
    mockRequest.setProtocol("http");
    mockRequest.setServerName("localhost");
    mockResponse.setStatus(HttpServletResponse.SC_OK);

    mockRequest.setUserPrincipal(new Principal() {

        public String getName() {
            return TEST_USER;
        }/*  w  w  w.j av a 2 s.co  m*/
    });

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, new StubSessionUser());
    mockRequest.setSession(session);

    // Set up the security label fixture
    // Setup the security label 
    eslFixture = new EnhancedSecurityLabel(TEST_PROTECTIVE_MARKING);

    eslFixture.setNationalityOwner(TEST_NATIONALITY_OWNER);
    eslFixture.setNationalityCaveats(TEST_NATIONALITY_CAVEATS);
    eslFixture.setCaveat(TEST_FREEFORM_CAVEAT);
    eslFixture.addOpenGroup(TEST_OPEN_GROUP1);
    eslFixture.addOpenGroup(TEST_OPEN_GROUP2);
    eslFixture.addClosedGroup(TEST_CLOSED_GROUP1);
    eslFixture.addClosedGroup(TEST_CLOSED_GROUP2);
    eslFixture.addOrganisation(TEST_ORGANISATION1);
    eslFixture.addOrganisation(TEST_ORGANISATION2);

    // Initialise the empty ESL
    emptyESL = new EnhancedSecurityLabel();
}

From source file:org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationFilter.java

@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    boolean requestCompleted = false;
    UserGroupInformation ugi = null;//from www  . ja  va  2s. c o m
    AuthenticationToken authToken = (AuthenticationToken) request.getUserPrincipal();
    if (authToken != null && authToken != AuthenticationToken.ANONYMOUS) {
        // if the request was authenticated because of a delegation token,
        // then we ignore proxyuser (this is the same as the RPC behavior).
        ugi = (UserGroupInformation) request
                .getAttribute(DelegationTokenAuthenticationHandler.DELEGATION_TOKEN_UGI_ATTRIBUTE);
        if (ugi == null) {
            String realUser = request.getUserPrincipal().getName();
            ugi = UserGroupInformation.createRemoteUser(realUser, handlerAuthMethod);
            String doAsUser = getDoAs(request);
            if (doAsUser != null) {
                ugi = UserGroupInformation.createProxyUser(doAsUser, ugi);
                try {
                    ProxyUsers.authorize(ugi, request.getRemoteAddr());
                } catch (AuthorizationException ex) {
                    HttpExceptionUtils.createServletExceptionResponse(response,
                            HttpServletResponse.SC_FORBIDDEN, ex);
                    requestCompleted = true;
                }
            }
        }
        UGI_TL.set(ugi);
    }
    if (!requestCompleted) {
        final UserGroupInformation ugiF = ugi;
        try {
            request = new HttpServletRequestWrapper(request) {

                @Override
                public String getAuthType() {
                    return (ugiF != null) ? handlerAuthMethod.toString() : null;
                }

                @Override
                public String getRemoteUser() {
                    return (ugiF != null) ? ugiF.getShortUserName() : null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return (ugiF != null) ? new Principal() {
                        @Override
                        public String getName() {
                            return ugiF.getUserName();
                        }
                    } : null;
                }
            };
            super.doFilter(filterChain, request, response);
        } finally {
            UGI_TL.remove();
        }
    }
}

From source file:org.ambraproject.web.DummySSOFilter.java

protected HttpServletRequest wrapRequest(HttpServletRequest request, final String user) {
    final Principal principal = (user == null) ? null : new Principal() {
        public String getName() {
            return user;
        }//from ww  w  . j a va 2  s  .co  m
    };

    return new HttpServletRequestWrapper(request) {
        public String getRemoteUser() {
            return user;
        }

        public Principal getUserPrincipal() {
            return principal;
        }
    };
}

From source file:org.apache.ambari.server.security.authorization.AmbariAuthorizationFilter.java

/**
 * Creates the default Authentication if a default user is configured
 *
 * @return an Authentication representing the default user
 *///from  w ww  .j  av a  2  s  .c  o m
private Authentication getDefaultAuthentication() {
    Authentication defaultUser = null;

    if ((configuration != null) && (users != null)) {
        String username = configuration.getDefaultApiAuthenticatedUser();

        if (!StringUtils.isEmpty(username)) {
            final User user = users.getUser(username, UserType.LOCAL);

            if (user != null) {
                Principal principal = new Principal() {
                    @Override
                    public String getName() {
                        return user.getUserName();
                    }
                };

                defaultUser = new UsernamePasswordAuthenticationToken(principal, null,
                        users.getUserAuthorities(user.getUserName(), user.getUserType()));
            }
        }
    }

    return defaultUser;
}

From source file:org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTFederationFilter.java

private Subject createSubjectFromToken(JWTToken token) {
    final String principal = token.getPrincipal();

    HashSet emptySet = new HashSet();
    Set<Principal> principals = new HashSet<Principal>();
    Principal p = new Principal() {
        @Override/*from   w  w  w.  j  av a 2 s . c o  m*/
        public String getName() {
            return principal;
        }
    };
    principals.add(p);

    //        The newly constructed Sets check whether this Subject has been set read-only 
    //        before permitting subsequent modifications. The newly created Sets also prevent 
    //        illegal modifications by ensuring that callers have sufficient permissions.
    //
    //        To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
    //        To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
    //        To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
    return subject;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServices.java

@Test
public void testDumpingSchedulerLogs() throws Exception {

    ResourceManager mockRM = mock(ResourceManager.class);
    Configuration conf = new YarnConfiguration();
    HttpServletRequest mockHsr = mock(HttpServletRequest.class);
    ApplicationACLsManager aclsManager = new ApplicationACLsManager(conf);
    when(mockRM.getApplicationACLsManager()).thenReturn(aclsManager);
    RMWebServices webSvc = new RMWebServices(mockRM, conf, mock(HttpServletResponse.class));

    // nothing should happen
    webSvc.dumpSchedulerLogs("1", mockHsr);
    Thread.sleep(1000);//from  ww w .ja v  a  2s. co m
    checkSchedulerLogFileAndCleanup();

    conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true);
    conf.setStrings(YarnConfiguration.YARN_ADMIN_ACL, "admin");
    aclsManager = new ApplicationACLsManager(conf);
    when(mockRM.getApplicationACLsManager()).thenReturn(aclsManager);
    webSvc = new RMWebServices(mockRM, conf, mock(HttpServletResponse.class));
    boolean exceptionThrown = false;
    try {
        webSvc.dumpSchedulerLogs("1", mockHsr);
        fail("Dumping logs should fail");
    } catch (ForbiddenException ae) {
        exceptionThrown = true;
    }
    assertTrue("ForbiddenException expected", exceptionThrown);
    exceptionThrown = false;
    when(mockHsr.getUserPrincipal()).thenReturn(new Principal() {
        @Override
        public String getName() {
            return "testuser";
        }
    });
    try {
        webSvc.dumpSchedulerLogs("1", mockHsr);
        fail("Dumping logs should fail");
    } catch (ForbiddenException ae) {
        exceptionThrown = true;
    }
    assertTrue("ForbiddenException expected", exceptionThrown);

    when(mockHsr.getUserPrincipal()).thenReturn(new Principal() {
        @Override
        public String getName() {
            return "admin";
        }
    });
    webSvc.dumpSchedulerLogs("1", mockHsr);
    Thread.sleep(1000);
    checkSchedulerLogFileAndCleanup();
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

/**
  */*from  w w  w.  j a  va 2  s . c  om*/
  */
public String authenticate(final String userID, final String credential) throws AuthenticationException {
    if (userID == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID));
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        // Create a principal for the userID
        Principal principal = new Principal() {
            public String getName() {
                return userID;
            }
        };

        if (!authManager.isValid(principal, credential)) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials"));
        } else {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, userID);
            if (publisher == null) {
                publisher = new Publisher();
                publisher.setAuthorizedName(userID);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(199);
                publisher.setMaxBusinesses(100);
                publisher.setMaxServicesPerBusiness(100);
                publisher.setMaxTmodels(100);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        }
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return userID;
}

From source file:org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabaseTest.java

/** **** Test Methods ************** */

public void testCreatePrincipal() {
    File testFile = createPasswordFile(1, 0);

    loadPasswordFile(testFile);//from   www .  j  av a2s  . c  o m

    Principal principal = new Principal() {
        public String getName() {
            return USERNAME;
        }
    };

    assertTrue("New user not created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));

    PasswordCallback callback = new PasswordCallback("prompt", false);
    try {
        _database.setPassword(principal, callback);
    } catch (AccountNotFoundException e) {
        fail("user account did not exist");
    }
    assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));

    loadPasswordFile(testFile);

    try {
        _database.setPassword(principal, callback);
    } catch (AccountNotFoundException e) {
        fail("user account did not exist");
    }
    assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));

    assertNotNull("Created User was not saved", _database.getUser(USERNAME));

    assertFalse("Duplicate user created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));
}

From source file:org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabaseTest.java

public void testCreatePrincipalIsSavedToFile() {

    File testFile = createPasswordFile(1, 0);

    loadPasswordFile(testFile);/*from   w w w .ja  v  a 2s .  c  o m*/

    final String CREATED_PASSWORD = "guest";
    final String CREATED_B64MD5HASHED_PASSWORD = "CE4DQ6BIb/BVMN9scFyLtA==";
    final String CREATED_USERNAME = "createdUser";

    Principal principal = new Principal() {
        public String getName() {
            return CREATED_USERNAME;
        }
    };

    _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray());

    try {
        BufferedReader reader = new BufferedReader(new FileReader(testFile));

        assertTrue("File has no content", reader.ready());

        assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());

        assertTrue("File is missing user data.", reader.ready());

        String userLine = reader.readLine();

        String[] result = Pattern.compile(":").split(userLine);

        assertEquals("User line not complete '" + userLine + "'", 2, result.length);

        assertEquals("Username not correct,", CREATED_USERNAME, result[0]);
        assertEquals("Password not correct,", CREATED_B64MD5HASHED_PASSWORD, result[1]);

        assertFalse("File has more content", reader.ready());

    } catch (IOException e) {
        fail("Unable to valdate file contents due to:" + e.getMessage());
    }
}