Java Code Examples for java.security.Principal

The following are top voted examples for showing how to use java.security.Principal. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: multi-tenant-rest-api   File: ResourcesController.java   Source Code and License 7 votes vote down vote up
@PreAuthorize("@roleChecker.hasValidRole(#principal, #companyid)")
@RequestMapping(value="/company/{companyid}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CompanyDTO> getCompany(
		Principal principal,
		@PathVariable String companyid) {
	
	// Check for SUPERADMIN and COMPANYADMIN role
	// RoleChecker.hasValidRole(principal, companyid);
	
	CompanyDTO companyDTO = companyService.findByName(companyid);
	if (companyDTO == null) {
		throw new ResourceNotFoundException();
	}
	
	return new ResponseEntity<CompanyDTO>(companyDTO, HttpStatus.OK);
}
 
Example 2
Project: trellis-rosid   File: AnonymousAuthFilterTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testAuthFilter() throws IOException {
    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();

    when(mockContext.getHeaders()).thenReturn(headers);

    final AuthFilter<String, Principal> filter = new AnonymousAuthFilter.Builder()
        .setAuthenticator(new AnonymousAuthenticator()).buildAuthFilter();
    filter.filter(mockContext);

    verify(mockContext).setSecurityContext(securityCaptor.capture());

    assertEquals(Trellis.AnonymousAgent.getIRIString(), securityCaptor.getValue().getUserPrincipal().getName());
    assertFalse(securityCaptor.getValue().isUserInRole("role"));
    assertFalse(securityCaptor.getValue().isSecure());
    assertEquals("NONE", securityCaptor.getValue().getAuthenticationScheme());
}
 
Example 3
Project: openjdk-jdk10   File: JaasClient.java   Source Code and License 6 votes vote down vote up
private static void checkPrincipal(LoginContext loginContext,
        boolean principalShouldExist) {
    if (!principalShouldExist) {
        if (loginContext.getSubject().getPrincipals().size() != 0) {
            throw new RuntimeException("Test failed. Principal was not "
                    + "cleared.");
        }
        return;
    }
    for (Principal p : loginContext.getSubject().getPrincipals()) {
        if (p instanceof UserPrincipal
                && USER_NAME.equals(p.getName())) {
            //Proper principal was found, return.
            return;
        }
    }
    throw new RuntimeException("Test failed. UserPrincipal "
            + USER_NAME + " expected.");

}
 
Example 4
Project: BiglyBT   File: AttributeCertificateIssuer.java   Source Code and License 6 votes vote down vote up
/**
 * Return any principal objects inside the attribute certificate issuer
 * object.
 *
 * @return an array of Principal objects (usually X500Principal)
 */
public Principal[] getPrincipals()
{
    Object[] p = this.getNames();
    List l = new ArrayList();

    for (int i = 0; i != p.length; i++)
    {
        if (p[i] instanceof Principal)
        {
            l.add(p[i]);
        }
    }

    return (Principal[])l.toArray(new Principal[l.size()]);
}
 
Example 5
Project: tomcat7   File: DataSourceRealm.java   Source Code and License 6 votes vote down vote up
/**
 * Return the Principal associated with the given user name.
 */
@Override
protected Principal getPrincipal(String username) {
    Connection dbConnection = open();
    if (dbConnection == null) {
        return new GenericPrincipal(username, null, null);
    }
    try {
        return (new GenericPrincipal(username,
                getPassword(dbConnection, username),
                getRoles(dbConnection, username)));
    } finally {
        close(dbConnection);
    }

}
 
Example 6
Project: microprofile-jwt-auth   File: ServiceServlet.java   Source Code and License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Principal user = req.getUserPrincipal();
    String pathInfo = req.getPathInfo();
    System.out.printf("pathInfo=%s\n", pathInfo);

    String result = "";
    if(pathInfo.endsWith("/getSubject")) {
        System.out.printf("Calling getSubject\n");
        result = getSubject(resp);
    }
    else {
        System.out.printf("Calling getPrincipalClass\n");
        result = getPrincipalClass(user);
    }
    resp.getWriter().write(result);
}
 
Example 7
Project: joai-project   File: SimpleLogin.java   Source Code and License 6 votes vote down vote up
/**
 *  This method is called if the LoginContext's overall authentication
 *  succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL
 *  LoginModules succeeded). <p>
 *
 *  If this LoginModule's own authentication attempt succeeded (checked by
 *  retrieving the private state saved by the <code>login</code> method), then
 *  this method associates a number of <code>NTPrincipal</code>s with the
 *  <code>Subject</code> located in the <code>LoginModule</code>. If this
 *  LoginModule's own authentication attempted failed, then this method removes
 *  any state that was originally saved. 
 *
 * @return                     true if this LoginModule's own login and commit
 *      attempts succeeded, or false otherwise.
 * @exception  LoginException  if the commit fails.
 */
public boolean commit() throws LoginException {
	if (pending == null) {
		return false;
	}

	principals = new Vector();
	Set s = subject.getPrincipals();

	for (int p = 0; p < pending.size(); p++) {
		putPrincipal(s, (Principal) pending.get(p));
	}

	commitSucceeded = true;
	prtln("\n COMMITTED (set commitSucceeded to true)");
	return true;
}
 
Example 8
Project: oscm   File: TagServiceWSTest.java   Source Code and License 6 votes vote down vote up
private WebServiceContext createWebServiceContextMock(String expectedIP,
        String expectedUser) {
    requestMock = mock(HttpServletRequest.class);
    when(requestMock.getRemoteAddr()).thenReturn(expectedIP);

    Principal principalMock = mock(Principal.class);
    when(principalMock.getName()).thenReturn(expectedUser);

    MessageContext msgContextMock = mock(MessageContext.class);
    when(msgContextMock.get(anyString())).thenReturn(requestMock);

    WebServiceContext wsContextMock = mock(WebServiceContext.class);
    when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
    when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);

    return wsContextMock;
}
 
Example 9
Project: saluki   File: AccessConfirmationController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
	ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
	model.put("auth_request", clientAuth);
	model.put("client", client);
	Map<String, String> scopes = new LinkedHashMap<String, String>();
	for (String scope : clientAuth.getScope()) {
		scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("authorize", model);
}
 
Example 10
Project: shibboleth-idp-oidc-extension   File: SelectAuthenticationFlowTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestNoneActive() {
    final AuthenticationContext authCtx = prc.getSubcontext(AuthenticationContext.class);
    final List<Principal> principals = Arrays.<Principal> asList(new TestPrincipal("test3"));
    final RequestedPrincipalContext rpc = new RequestedPrincipalContext();
    rpc.getPrincipalEvalPredicateFactoryRegistry().register(TestPrincipal.class, "exact",
            new ExactPrincipalEvalPredicateFactory());
    rpc.setOperator("exact");
    rpc.setRequestedPrincipals(principals);
    authCtx.addSubcontext(rpc, true);
    authCtx.getPotentialFlows().get("test3").setSupportedPrincipals(principals);

    action.execute(src);

    Assert.assertNull(authCtx.getAuthenticationResult());
    Assert.assertEquals(authCtx.getAttemptedFlow().getId(), "test3");
}
 
Example 11
Project: monarch   File: ServerHandShakeProcessor.java   Source Code and License 6 votes vote down vote up
public static long setAuthAttributes(ServerConnection connection) throws Exception {
  try {
    logger.debug("setAttributes()");
    Object principal = ((HandShake) connection.getHandshake()).verifyCredentials();

    long uniqueId;
    if (principal instanceof Subject) {
      uniqueId =
          connection.getClientUserAuths(connection.getProxyID()).putSubject((Subject) principal);
    } else {
      // this sets principal in map as well....
      uniqueId = getUniqueId(connection, (Principal) principal);
      connection.setPrincipal((Principal) principal);// TODO:hitesh is this require now ???
    }
    return uniqueId;
  } catch (Exception ex) {
    throw ex;
  }
}
 
Example 12
Project: cyberduck   File: AbstractX509KeyManager.java   Source Code and License 6 votes vote down vote up
/**
 * @param issuers The list of acceptable CA issuer subject names or null if it does not matter which issuers are used
 * @return True if certificate matches issuer and key type
 */
protected boolean matches(final Certificate c, final String[] keyTypes, final Principal[] issuers) {
    if(!(c instanceof X509Certificate)) {
        log.warn(String.format("Certificate %s is not of type X509", c));
        return false;
    }
    if(!Arrays.asList(keyTypes).contains(c.getPublicKey().getAlgorithm())) {
        log.warn(String.format("Key type %s does not match any of %s", c.getPublicKey().getAlgorithm(),
                Arrays.toString(keyTypes)));
        return false;
    }
    if(null == issuers || Arrays.asList(issuers).isEmpty()) {
        // null if it does not matter which issuers are used
        return true;
    }
    final X500Principal issuer = ((X509Certificate) c).getIssuerX500Principal();
    if(!Arrays.asList(issuers).contains(issuer)) {
        log.warn(String.format("Issuer %s does not match", issuer));
        return false;
    }
    return true;
}
 
Example 13
Project: tomcat7   File: TestJNDIRealm.java   Source Code and License 6 votes vote down vote up
@Test
public void testAuthenticateWithUserPasswordAndDigest() throws Exception {
    // GIVEN
    JNDIRealm realm = buildRealm(ha1(), "MD5");
    realm.setUserPassword(USER_PASSWORD_ATTR);

    // WHEN
    String expectedResponse =
            MD5Encoder.encode(md5Helper.digest((ha1() + ":" + NONCE + ":" + HA2).getBytes()));
    Principal principal =
            realm.authenticate(USER, expectedResponse, NONCE, null, null, null, REALM, HA2);

    // THEN
    Assert.assertTrue(principal instanceof GenericPrincipal);
    Assert.assertEquals(ha1(), ((GenericPrincipal)principal).getPassword());
}
 
Example 14
Project: saluki   File: TokenController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/oauth/tokens/revoke.html", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String revokeToken(@RequestParam("user") String user, @RequestParam("token") String token,
                          Principal principal) throws Exception {
    checkResourceOwner(user, principal);
    if (tokenServices.revokeToken(token)) {
        return "redirect:/oauth/tokens.html?revoke-success";
    } else {
        return "redirect:/oauth/tokens.html?revoke-empty";
    }
}
 
Example 15
Project: monarch   File: SocketCreator.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
  if (!StringUtils.isEmpty(this.keyAlias)) {
    PrivateKey key = this.delegate.getPrivateKey(this.keyAlias);
    return getKeyAlias(keyType, key);
  }
  return this.delegate.chooseServerAlias(keyType, issuers, socket);

}
 
Example 16
Project: calcite-avatica   File: SpnegoTestUtil.java   Source Code and License 5 votes vote down vote up
@Override public void handle(String target, Request baseRequest, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
  Authentication auth = baseRequest.getAuthentication();
  if (Authentication.UNAUTHENTICATED == auth) {
    throw new AssertionError("Unauthenticated users should not reach here!");
  }

  baseRequest.setHandled(true);
  UserAuthentication userAuth = (UserAuthentication) auth;
  UserIdentity userIdentity = userAuth.getUserIdentity();
  Principal userPrincipal = userIdentity.getUserPrincipal();

  response.getWriter().print("OK " + userPrincipal.getName());
  response.setStatus(200);
}
 
Example 17
Project: tomcat7   File: JAASRealm.java   Source Code and License 5 votes vote down vote up
/**
 * Return the <code>Principal</code> associated with the given user name.
 */
@Override
protected Principal getPrincipal(String username) {

    return authenticate(username,
            new JAASCallbackHandler(this, username, null, null, null, null,
                    null, null, null, HttpServletRequest.CLIENT_CERT_AUTH));

}
 
Example 18
Project: openjdk-jdk10   File: SimpleStandard.java   Source Code and License 5 votes vote down vote up
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the principalName identity.
 */
private void checkSubject(String op) {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals(principalName))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
Example 19
Project: GitHub   File: CacheTest.java   Source Code and License 5 votes vote down vote up
@Test public void secureResponseCaching() throws IOException {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setBody("ABC"));

  client = client.newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
      .build();

  Request request = new Request.Builder().url(server.url("/")).build();
  Response response1 = client.newCall(request).execute();
  BufferedSource in = response1.body().source();
  assertEquals("ABC", in.readUtf8());

  // OpenJDK 6 fails on this line, complaining that the connection isn't open yet
  CipherSuite cipherSuite = response1.handshake().cipherSuite();
  List<Certificate> localCerts = response1.handshake().localCertificates();
  List<Certificate> serverCerts = response1.handshake().peerCertificates();
  Principal peerPrincipal = response1.handshake().peerPrincipal();
  Principal localPrincipal = response1.handshake().localPrincipal();

  Response response2 = client.newCall(request).execute(); // Cached!
  assertEquals("ABC", response2.body().string());

  assertEquals(2, cache.requestCount());
  assertEquals(1, cache.networkCount());
  assertEquals(1, cache.hitCount());

  assertEquals(cipherSuite, response2.handshake().cipherSuite());
  assertEquals(localCerts, response2.handshake().localCertificates());
  assertEquals(serverCerts, response2.handshake().peerCertificates());
  assertEquals(peerPrincipal, response2.handshake().peerPrincipal());
  assertEquals(localPrincipal, response2.handshake().localPrincipal());
}
 
Example 20
Project: jdk8u-jdk   File: StartTlsResponseImpl.java   Source Code and License 5 votes vote down vote up
private static Principal getPeerPrincipal(SSLSession session)
        throws SSLPeerUnverifiedException {
    Principal principal;
    try {
        principal = session.getPeerPrincipal();
    } catch (AbstractMethodError e) {
        // if the JSSE provider does not support it, return null, since
        // we need it only for Kerberos.
        principal = null;
    }
    return principal;
}
 
Example 21
Project: lazycat   File: CombinedRealm.java   Source Code and License 5 votes vote down vote up
/**
 * Return the Principal associated with the specified chain of X509 client
 * certificates. If there is none, return <code>null</code>.
 *
 * @param certs
 *            Array of client certificates, with the first one in the array
 *            being the certificate of the client itself.
 */
@Override
public Principal authenticate(X509Certificate[] certs) {
	Principal authenticatedUser = null;
	String username = null;
	if (certs != null && certs.length > 0) {
		username = certs[0].getSubjectDN().getName();
	}

	for (Realm realm : realms) {
		if (log.isDebugEnabled()) {
			log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
		}

		authenticatedUser = realm.authenticate(certs);

		if (authenticatedUser == null) {
			if (log.isDebugEnabled()) {
				log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
			}
		} else {
			if (log.isDebugEnabled()) {
				log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
			}
			break;
		}
	}
	return authenticatedUser;
}
 
Example 22
Project: jdk8u-jdk   File: AbstractDelegateHttpsURLConnection.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the principal the client sent to the
 * server, or null if the client did not authenticate.
 */
Principal getLocalPrincipal()
{
    if (cachedResponse != null) {
        return ((SecureCacheResponse)cachedResponse).getLocalPrincipal();
    }

    if (http == null) {
        throw new IllegalStateException("connection not yet open");
    } else {
        return (((HttpsClient)http).getLocalPrincipal());
    }
}
 
Example 23
Project: uis   File: StudentCourseRegistrationController.java   Source Code and License 5 votes vote down vote up
@PostMapping("/unregister")
public String unregisterStudent(@RequestParam Long course,
                                RedirectAttributes redirectAttributes,
                                Principal principal) {
    Student student = studentService.findByUsername(principal.getName());
    Course courseToUnregister = courseService.unregisterStudentFromCourse(student, course);

    String successMsg = messages.msg("student.my.courses.unregister.success", courseToUnregister.getSubject().getName());
    redirectAttributes.addFlashAttribute("flashMessageNotLocalized", successMsg);
    return "redirect:/student/myCourses";
}
 
Example 24
Project: OpenJSharp   File: SubjectDelegator.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the {@linkplain Subject} principals
 * @param subject The subject
 * @return If the {@code Subject} is immutable it will return the principals directly.
 *         If the {@code Subject} is mutable it will create an unmodifiable copy.
 */
private static Collection<Principal> getSubjectPrincipals(Subject subject) {
    if (subject.isReadOnly()) {
        return subject.getPrincipals();
    }

    List<Principal> principals = Arrays.asList(subject.getPrincipals().toArray(new Principal[0]));
    return Collections.unmodifiableList(principals);
}
 
Example 25
Project: agroal   File: ConnectionFactory.java   Source Code and License 5 votes vote down vote up
private void setupSecurity(AgroalConnectionFactoryConfiguration configuration) {
    Principal principal = configuration.principal();

    if ( principal == null ) {
        // skip!
    } else if ( principal instanceof NamePrincipal ) {
        jdbcProperties.put( USER_PROPERTY_NAME, principal.getName() );
    }

    // Add other principal types here

    else {
        throw new IllegalArgumentException( "Unknown Principal type: " + principal.getClass().getName() );
    }

    for ( Object credential : configuration.credentials() ) {
        if ( credential instanceof SimplePassword ) {
            jdbcProperties.put( PASSWORD_PROPERTY_NAME, ( (SimplePassword) credential ).getWord() );
        }

        // Add other credential types here

        else {
            throw new IllegalArgumentException( "Unknown Credential type: " + credential.getClass().getName() );
        }
    }
}
 
Example 26
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getServerAliases() {
    String s = "";
    Principal[] principals = new Principal[0];

    String alias1 = "alias1";
    when(this.keyManager1.getServerAliases(s, principals)).thenReturn(new String[]{alias1});

    String alias2 = "alias2";
    when(this.keyManager2.getServerAliases(s, principals)).thenReturn(new String[]{alias2});

    assertThat(this.delegatingKeyManager.getServerAliases(s, principals)).contains(alias1, alias2);
}
 
Example 27
Project: OpenJSharp   File: SubjectDelegator.java   Source Code and License 5 votes vote down vote up
public AccessControlContext
    delegatedContext(AccessControlContext authenticatedACC,
                     Subject delegatedSubject,
                     boolean removeCallerContext)
        throws SecurityException {

    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }

    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for(Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action =
        new PrivilegedAction<Void>() {
            public Void run() {
                for (Permission sdp : permissions) {
                    AccessController.checkPermission(sdp);
                }
                return null;
            }
        };
    AccessController.doPrivileged(action, authenticatedACC);

    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}
 
Example 28
Project: FirefoxData-android   File: SSLContextBuilder.java   Source Code and License 5 votes vote down vote up
public String chooseServerAlias(
        final String keyType, final Principal[] issuers, final Socket socket) {
    final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>();
    final String[] aliases = this.keyManager.getServerAliases(keyType, issuers);
    if (aliases != null) {
        for (final String alias: aliases) {
            validAliases.put(alias,
                    new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
        }
    }
    return this.aliasStrategy.chooseAlias(validAliases, socket);
}
 
Example 29
Project: apache-tomcat-7.0.73-with-comment   File: TestMemoryRealm.java   Source Code and License 5 votes vote down vote up
/**
 * Unknown user triggers NPE.
 */
@Test
public void testBug56246() {
    MemoryRealm memoryRealm = new MemoryRealm();

    Principal p = memoryRealm.authenticate("foo", "bar");

    Assert.assertNull(p);
}
 
Example 30
Project: akir   File: LoginController.java   Source Code and License 5 votes vote down vote up
@GetMapping
public String loginPage(ModelMap model, Principal principal, HttpServletRequest request, HttpServletResponse response) {
	OneTimeCookie.consume(request, response, LOGIN_RETURN_URL)
			.map(ReturnableLoginUrlAuthenticationEntryPoint::decodeReturnUrl)
			.ifPresent(returnUrl -> model.addAttribute("login_return_url", returnUrl));

	OneTimeCookie.consume(request, response, LOGIN_TOOLTIP)
			.ifPresent(tooltip -> model.addAttribute("login_tooltip", tooltip));

	if (principal != null)
		return "redirect:/";

	return "login";
}
 
Example 31
Project: openjdk-jdk10   File: StartTlsResponseImpl.java   Source Code and License 5 votes vote down vote up
private static Principal getPeerPrincipal(SSLSession session)
        throws SSLPeerUnverifiedException {
    Principal principal;
    try {
        principal = session.getPeerPrincipal();
    } catch (AbstractMethodError e) {
        // if the JSSE provider does not support it, return null, since
        // we need it only for Kerberos.
        principal = null;
    }
    return principal;
}
 
Example 32
Project: spring-boot-shopping-cart   File: LoginController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/login")
public String login(Principal principal) {
    if (principal != null) {
        return "redirect:/home";
    }
    return "/login";
}
 
Example 33
Project: hadoop   File: TestKerberosAuthenticationHandler.java   Source Code and License 5 votes vote down vote up
@Test(timeout=60000)
public void testDynamicPrincipalDiscovery() throws Exception {
  String[] keytabUsers = new String[]{
      "HTTP/host1", "HTTP/host2", "HTTP2/host1", "XHTTP/host"
  };
  String keytab = KerberosTestUtils.getKeytabFile();
  getKdc().createPrincipal(new File(keytab), keytabUsers);

  // destroy handler created in setUp()
  handler.destroy();
  Properties props = new Properties();
  props.setProperty(KerberosAuthenticationHandler.KEYTAB, keytab);
  props.setProperty(KerberosAuthenticationHandler.PRINCIPAL, "*");
  handler = getNewAuthenticationHandler();
  handler.init(props);

  Assert.assertEquals(KerberosTestUtils.getKeytabFile(), handler.getKeytab());    
  
  Set<KerberosPrincipal> loginPrincipals = handler.getPrincipals();
  for (String user : keytabUsers) {
    Principal principal = new KerberosPrincipal(
        user + "@" + KerberosTestUtils.getRealm());
    boolean expected = user.startsWith("HTTP/");
    Assert.assertEquals("checking for "+user, expected, 
        loginPrincipals.contains(principal));
  }
}
 
Example 34
Project: apache-tomcat-7.0.73-with-comment   File: NioX509KeyManager.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
        SSLEngine engine) {
    if (serverKeyAlias!=null) {
        return serverKeyAlias;
    }

    return super.chooseEngineServerAlias(keyType, issuers, engine);
}
 
Example 35
Project: jerrydog   File: SingleSignOn.java   Source Code and License 5 votes vote down vote up
public SingleSignOnEntry(Principal principal, String authType,
                         String username, String password) {
    super();
    this.principal = principal;
    this.authType = authType;
    this.username = username;
    this.password = password;
}
 
Example 36
Project: springboot-shiro-cas-mybatis   File: X509CredentialsAuthenticationHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Does principal name match pattern?
 *
 * @param principal the principal
 * @param pattern the pattern
 * @return true, if successful
 */
private boolean doesNameMatchPattern(final Principal principal,
        final Pattern pattern) {
    final String name = principal.getName();
    final boolean result = pattern.matcher(name).matches();
    logger.debug(String.format("%s matches %s == %s", pattern.pattern(), name, result));
    return result;
}
 
Example 37
Project: cyberduck   File: DefaultX509KeyManager.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
    final javax.net.ssl.X509KeyManager manager;
    try {
        manager = this.getKeystore();
    }
    catch(IOException e) {
        return null;
    }
    return manager.chooseServerAlias(keyType, issuers, socket);
}
 
Example 38
Project: sentry   File: ActivityService.java   Source Code and License 5 votes vote down vote up
@SubscribeMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
    activityDTO.setUserLogin(SecurityUtils.getCurrentUserLogin());
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    Instant instant = Instant.ofEpochMilli(Calendar.getInstance().getTimeInMillis());
    activityDTO.setTime(dateTimeFormatter.format(ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault())));
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
}
 
Example 39
Project: oscm   File: TestSessionContext.java   Source Code and License 5 votes vote down vote up
@Override
public Principal getCallerPrincipal() {
    if (username == null) {
        return null;
    }
    return new Principal() {

        @Override
        public String getName() {
            return username;
        }
    };
}
 
Example 40
Project: microservices-event-sourcing   File: UserControllerV1.java   Source Code and License 5 votes vote down vote up
@RequestMapping(path = "/me")
public ResponseEntity<User> me(Principal principal) {
    User user = null;
    if(principal != null) {
        user = userService.getUserByUsername(principal.getName());
    }
    return Optional.ofNullable(user)
            .map(a -> new ResponseEntity<>(a, HttpStatus.OK))
            .orElseThrow(() -> new UsernameNotFoundException("Username not found"));
}