Authenticate with token bytes.

@param tokenBytes
@return The authenticated subject.
1429
@Override
    public Subject authenticate(@Sensitive byte[] tokenBytes) throws AuthenticationException {
        AuthenticationData authenticationData = createAuthenticationData(tokenBytes);
        return authenticationService.authenticate(jaasEntryName, authenticationData, null);
    }
899761
public Account authenticate(AuthenticationToken authenticationToken) {

        if (accountCache != null) {
            Account account = accountCache.getIfPresent(authenticationToken);
            if (account != null) {
                return account;
            }
        }

        Account authenticatedAccount = null;
        for (Realm realm : allRealms) {
            if (realm.canAuthenticate(authenticationToken)) {
                Account account = realm.authenticate(authenticationToken);
                if (account != null && !account.isDisabled()) {
                    // create a sanitized copy of this account
                    authenticatedAccount = new Account(account.getName(), account.getCredentials().sanitize());
                    break;
                }
            }
        }

        // no authentication
        if (authenticatedAccount == null) {
            return null;
        }

        // aggregate metadata, roles, & permissions
        final Account aggregateAccount = authenticatedAccount;
        allRealms.stream()
                .filter(realm -> realm.hasAccount(aggregateAccount.getUsername()))
                .map(realm -> realm.getAccount(aggregateAccount.getUsername()))
                .filter(account -> account.isEnabled())
                .forEach(account -> {
                    if (Strings.isNullOrEmpty(aggregateAccount.getName())) {
                        aggregateAccount.setName(account.getName());
                    }
                    aggregateAccount.addEmailAddresses(account.getEmailAddresses());
                    aggregateAccount.addTokens(account.getTokens());
                    aggregateAccount.getAuthorizations()
                            .addRoles(account.getAuthorizations().getRoles())
                            .addPermissions(account.getAuthorizations().getPermissions());
                });

        if (accountCache != null) {
            // cache this assembled account
            accountCache.put(authenticationToken, aggregateAccount);
        }

        return aggregateAccount;
    }
1214554
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(OAUTH2_ACTION)) {
			String authCode = request.getParameter("code");
			if (!StringUtils.isBlank(authCode)) {
				String appid = SecurityUtils.getAppidFromAuthRequest(request);
				String redirectURI = SecurityUtils.getRedirectUrl(request);
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.OAUTH2_PREFIX);
				String entity = Utils.formatMessage(PAYLOAD,
						authCode, Utils.urlEncode(redirectURI),
						URLEncoder.encode(SecurityUtils.getSettingForApp(app, "security.oauth.scope", ""), "UTF-8"),
						keys[0], keys[1]);

				String acceptHeader = SecurityUtils.getSettingForApp(app, "security.oauth.accept_header", "");
				HttpPost tokenPost = new HttpPost(SecurityUtils.getSettingForApp(app, "security.oauth.token_url", ""));
				tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
				tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
				if (!StringUtils.isBlank(acceptHeader)) {
					tokenPost.setHeader(HttpHeaders.ACCEPT, acceptHeader);
				}

				try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
					if (resp1 != null && resp1.getEntity() != null) {
						Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
						if (token != null && token.containsKey("access_token")) {
							userAuth = getOrCreateUser(app, (String) token.get("access_token"));
						}
						EntityUtils.consumeQuietly(resp1.getEntity());
					}
				}
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
1203200
@Override
    public IdentityToken encodeIdentityToken(Codec codec) {
        IdentityToken token = null;

        SubjectManager subjectManager = new SubjectManager();
        Subject subject = subjectManager.getInvocationSubject();
        if (subject == null) {
            subject = subjectManager.getCallerSubject();
        }

        Set<WSPrincipal> principals = subject.getPrincipals(WSPrincipal.class);
        Principal principal = (principals.isEmpty()) ? null : principals.iterator().next();

        // There must be a WSPrincipal in the subject, but check for null to satisfy findbugs
        if (principal != null) {

            Any any = ORB.init().create_any();

            //TODO consider including a domain in this scoped-username
            String principalName = principal.getName();
            GSS_NT_ExportedNameHelper.insert(any, Util.encodeGSSExportName(oid, principalName));

            byte[] encoding = null;
            try {
                encoding = codec.encode_value(any);
            } catch (InvalidTypeForEncoding itfe) {
                throw new IllegalStateException("Unable to encode principal name '" + principalName + "' " + itfe, itfe);
            }

            token = new IdentityToken();
            token.principal_name(encoding);
        } else {
            token = new IdentityToken();
            token.anonymous(true);
        }

        return token;
    }
418240
Map<String,Long> getContext(String... tokens) throws IOException {
    Objects.requireNonNull(tokens);
    TermsEnum iterator = getIterator();
    Map<String,Long> result = new HashMap<>();
    BytesRef byteRef;
    int i = 0;
    while ((byteRef = iterator.next()) != null) {
      String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
      for (String token : tokens) {
        if (term.contains(" " + token + " ")) {
          String[] split = term.split(" ");
          if (split.length == 3) {
            long count = getCount(Arrays.asList(split[0], split[1], split[2]));
            result.put(term, count);
          }
        }
      }
      /*if (i++ > 1_000_000) { // comment in for faster testing with subsets of the data
        break;
      }*/
    }
    return result;
  }
176982
@Override
	public byte[] bytes() {
		return concat(b64UrlEncode(header.bytes()), JwtHelper.PERIOD,
				b64UrlEncode(content), JwtHelper.PERIOD, b64UrlEncode(crypto));
	}
533320
public void authenticate() {
        URL url;
        try {
            url = new URL(this.getTokenURL());
        } catch (MalformedURLException e) {
            assert false : "An invalid token URL indicates a bug in the SDK.";
            throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e);
        }

        String jwtAssertion = this.constructJWTAssertion();

        String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

        BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
        request.shouldAuthenticate(false);
        request.setBody(urlParameters);

        String json;
        try {
            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        } catch (BoxAPIException ex) {
            // Use the Date advertised by the Box server as the current time to synchronize clocks
            List<String> responseDates = ex.getHeaders().get("Date");
            NumericDate currentTime;
            if (responseDates != null) {
                String responseDate = responseDates.get(0);
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
                try {
                    Date date = dateFormat.parse(responseDate);
                    currentTime = NumericDate.fromMilliseconds(date.getTime());
                } catch (ParseException e) {
                    currentTime = NumericDate.now();
                }
            } else {
                currentTime = NumericDate.now();
            }

            // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time
            jwtAssertion = this.constructJWTAssertion(currentTime);
            urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

            // Re-send the updated request
            request = new BoxAPIRequest(this, url, "POST");
            request.shouldAuthenticate(false);
            request.setBody(urlParameters);

            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        }

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.setAccessToken(jsonObject.get("access_token").asString());
        this.setLastRefresh(System.currentTimeMillis());
        this.setExpires(jsonObject.get("expires_in").asLong() * 1000);

        //if token cache is specified, save to cache
        if (this.accessTokenCache != null) {
            String key = this.getAccessTokenCacheKey();
            JsonObject accessTokenCacheInfo = new JsonObject()
                    .add("accessToken", this.getAccessToken())
                    .add("lastRefresh", this.getLastRefresh())
                    .add("expires", this.getExpires());

            this.accessTokenCache.put(key, accessTokenCacheInfo.toString());
        }
    }
458532
private AuthToken parseAuthorizationToken(String authHeader) {
        try {
            String tokenEncoded = authHeader.substring(11);
            return AuthTokenUtil.consumeToken(tokenEncoded);
        } catch (IllegalArgumentException e) {
            // TODO log this error
            return null;
        }
    }
366331
public Set<AuthorisationData> convertIdentifyingTokenList(Set<IdentifyingToken> tokens) {
        Set<AuthorisationData> resultList = new HashSet<>();

        for (IdentifyingToken token : tokens) {
            resultList.add(convertIdentifyingToken(token));
        }

        return resultList;
    }
1280919
public GitlabHTTPRequestor authenticate(String token, TokenType type, AuthMethod method) {
        this.apiToken = token;
        this.tokenType = type;
        this.authMethod = method;
        return this;
    }
1318980
public static byte[] decryptAsBytes(final byte[] encryptedIvTextBytes) throws Exception {
        final SecretKey secretKey = KeyManager.getInstance().getSecretKey();
        return decryptAsBytes(secretKey, encryptedIvTextBytes);
    }
351541
public static byte[] decrypt(byte[] cipherBytes) {
		try {
//			byte[] cipherBytes = toBytes(cipherText);
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
			SecretKeySpec key = new SecretKeySpec(ENCRYPTION_KEY.getBytes("UTF-8"), "AES");
			cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
			return cipher.doFinal(cipherBytes);
		} catch (Exception e) {
			throw new JKSecurityException(e);
		}
	}
417508
public static Token parseToken(byte[] secret, String token) {
        Token tk = new Token();
        if (S.blank(token)) return tk;
        String s = "";
        try {
            s = Crypto.decryptAES(token, secret);
        } catch (Exception e) {
            return tk;
        }
        String[] sa = s.split("\\|");
        if (sa.length < 2) return tk;
        tk.id = sa[0];
        try {
            tk.due = Long.parseLong(sa[1]);
            if (tk.expired()) {
                return tk;
            }
        } catch (Exception e) {
            tk.due = $.ms() - 1000 * 60 * 60 * 24;
            return tk;
        }
        if (sa.length > 2) {
            sa = Arrays.copyOfRange(sa, 2, sa.length);
            tk.payload.addAll(C.listOf(sa));
        }
        return tk;
    }
1336901
private IoBuffer encodeGSSAPIAuthenticationPacket(
            final SocksProxyRequest request) throws GSSException {
        GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT);
        if (ctx == null) {
            // first step in the authentication process
            GSSManager manager = GSSManager.getInstance();
            GSSName serverName = manager.createName(request
                    .getServiceKerberosName(), null);
            Oid krb5OID = new Oid(SocksProxyConstants.KERBEROS_V5_OID);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Available mechs:");
                for (Oid o : manager.getMechs()) {
                    if (o.equals(krb5OID)) {
                        LOGGER.debug("Found Kerberos V OID available");
                    }
                    LOGGER.debug("{} with oid = {}",
                            manager.getNamesForMech(o), o);
                }
            }

            ctx = manager.createContext(serverName, krb5OID, null,
                    GSSContext.DEFAULT_LIFETIME);

            ctx.requestMutualAuth(true); // Mutual authentication
            ctx.requestConf(false);
            ctx.requestInteg(false);

            getSession().setAttribute(GSS_CONTEXT, ctx);
        }

        byte[] token = (byte[]) getSession().getAttribute(GSS_TOKEN);
        if (token != null) {
            LOGGER.debug("  Received Token[{}] = {}", token.length,
                    ByteUtilities.asHex(token));
        }
        IoBuffer buf = null;

        if (!ctx.isEstablished()) {
            // token is ignored on the first call
            if (token == null) {
                token = new byte[32];
            }

            token = ctx.initSecContext(token, 0, token.length);

            // Send a token to the server if one was generated by
            // initSecContext
            if (token != null) {
                LOGGER.debug("  Sending Token[{}] = {}", token.length,
                        ByteUtilities.asHex(token));

                getSession().setAttribute(GSS_TOKEN, token);
                buf = IoBuffer.allocate(4 + token.length);
                buf.put(new byte[] {
                        SocksProxyConstants.GSSAPI_AUTH_SUBNEGOTIATION_VERSION,
                        SocksProxyConstants.GSSAPI_MSG_TYPE });

                buf.put(ByteUtilities.intToNetworkByteOrder(token.length, 2));
                buf.put(token);
            }
        }

        return buf;
    }
357669
public BytesWritableToken visitBytesWritable(EditsElement e) throws IOException {
    return (BytesWritableToken)visit(tokenizer.read(new BytesWritableToken(e)));
  }
171468
public static Collection<Token<? extends TokenIdentifier>> readTokensFromFile(Path tokenFilePath,
      Configuration configuration) throws IOException {
    return Credentials.readTokenStorageFile(tokenFilePath, configuration).getAllTokens();
  }
790410
public static Credential credential(
      AccessTokenProvider accessTokenProvider, Collection<String> scopes)
      throws IOException, GeneralSecurityException {
    return getCredentialFromAccessTokenProvider(accessTokenProvider, scopes);
  }