/*
(non-Javadoc)

@see javax.security.enterprise.SecurityContext#authenticate(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters)
513803
@Override
    public AuthenticationStatus authenticate(HttpServletRequest req, HttpServletResponse res, AuthenticationParameters params) {
        AuthenticationStatus authStatus = AuthenticationStatus.SEND_FAILURE;
        req.setAttribute(JavaEESecConstants.SECURITY_CONTEXT_AUTH_PARAMS, params);
        try {
            boolean result = req.authenticate(res);
            if (result) {
                authStatus = AuthenticationStatus.SUCCESS;
            } else {
//TODO some error handling.
            }
        } catch (Exception e) {
//TODO need to handle error.
            e.printStackTrace();
        }
        return authStatus;
    }
543534
@Override
  public Access authenticate() {
    try {
      JSONObject user = new JSONObject();
      user.put("id", mUserId);
      user.put("password", mPassword);
      JSONObject password = new JSONObject();
      password.put("user", user);
      JSONArray methods = new JSONArray();
      methods.add("password");
      JSONObject identity = new JSONObject();
      identity.put("methods", methods);
      identity.put("password", password);
      JSONObject project = new JSONObject();
      project.put("id", mProjectId);
      JSONObject scope = new JSONObject();
      scope.put("project", project);
      JSONObject auth = new JSONObject();
      auth.put("identity", identity);
      auth.put("scope", scope);
      JSONObject requestBody = new JSONObject();
      requestBody.put("auth", auth);
      HttpURLConnection connection =
          (HttpURLConnection) new URL(mAuthUrl).openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept", "application/json");
      connection.setRequestProperty("Content-Type", "application/json");
      OutputStream output = connection.getOutputStream();
      output.write(requestBody.toString().getBytes());
      HttpStatusChecker.verifyCode(STATUS_CHECKERS, connection.getResponseCode());
      final String res;
      try (final BufferedReader bufReader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        res = bufReader.readLine();
      }
      JSONParser parser = new JSONParser();
      JSONObject jsonResponse = (JSONObject) parser.parse(res);

      String token = connection.getHeaderField("X-Subject-Token");
      PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token,
          mPrefferedRegion);
      connection.disconnect();
      return access;
    } catch (IOException | ParseException e) {
      LOG.error(e.getMessage());
      throw new CommandException("Unable to execute the HTTP call or to convert the HTTP Response",
              e);
    }
  }
753362
protected final boolean authenticate(Context context, String username, String password, boolean rememberMe) {
        UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, password, rememberMe);
        try {
            SecurityUtils.getSubject().login(authenticationToken);
            log.info("'{}' authenticated", username);
            return true;
        } catch (AuthenticationException e) {
            log.info("'{}' failed to authenticate", username);
            return false;
        }
    }
720101
func (m *Middleware) Authenticate() http.Handler {
	generateHandler := func(w http.ResponseWriter, r *http.Request) *jwtError {
		if r.Method != "POST" {
			return &jwtError{
				status:  http.StatusBadRequest,
				err:     ErrInvalidMethod,
				message: "receiving request",
			}
		}

		b := make(map[string]string, 0)
		contentType := r.Header.Get("content-type")
		switch contentType {
		case "application/x-www-form-urlencoded", "application/x-www-form-urlencoded; charset=UTF-8":
			identity, verify := r.FormValue(m.identityField), r.FormValue(m.verifyField)
			if identity == "" || verify == "" {
				return &jwtError{
					status:  http.StatusInternalServerError,
					err:     ErrParsingCredentials,
					message: "parsing authorization",
				}
			}
			b[m.identityField], b[m.verifyField] = identity, verify
		default:
			err := json.NewDecoder(r.Body).Decode(&b)
			if err != nil {
				return &jwtError{
					status:  http.StatusInternalServerError,
					err:     ErrParsingCredentials,
					message: "parsing authorization",
				}
			}
		}

		// Check if required fields are in the body
		if _, ok := b[m.identityField]; !ok {
			return &jwtError{
				status:  http.StatusBadRequest,
				err:     ErrParsingCredentials,
				message: "parsing credentials, missing identity field",
			}
		}
		if _, ok := b[m.verifyField]; !ok {
			return &jwtError{
				status:  http.StatusBadRequest,
				err:     ErrParsingCredentials,
				message: "parsing credentials, missing verify field",
			}
		}
		err := m.auth(b[m.identityField], b[m.verifyField])
		if err != nil {
			return &jwtError{
				status:  http.StatusInternalServerError,
				err:     err,
				message: "performing authorization",
			}
		}
		response, err := m.CreateToken(b[m.identityField])
		if err != nil {
			return &jwtError{
				status:  http.StatusInternalServerError,
				err:     err,
				message: response,
			}
		}
		w.Write([]byte(response))
		return nil
	}

	return errorHandler(generateHandler)
}
306126
@Path("authenticate")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public TokenDto authenticate(@FormParam("username") String username, @FormParam("password") String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = this.authManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return new TokenDto(TokenUtils.createToken((UserDetails) authentication.getPrincipal()));
    }
928642
public AuthenticationResult authenticate(HttpServletRequest request) {
        HttpSession session = null;
        AuthenticationResult authResult = null;
        if (!HTTP_DONT_USE_SESSION && !m_dontUseSession) {
            try {
                session = request.getSession();
                if (session != null) {
                    if (session.isNew()) {
                        session.setMaxInactiveInterval(MAX_SESSION_INACTIVITY_SECONDS);
                    }
                    authResult = (AuthenticationResult )session.getAttribute(AUTH_USER_SESSION_KEY);
                }
            } catch (Exception ex) {
                //Use no session mode meaning whatever VMC sends as hashed password is used to authenticate.
                session = null;
                m_rate_limited_log.log(EstTime.currentTimeMillis(), Level.ERROR, ex, "Failed to get or create HTTP Session. authenticating user explicitely.");
            }
        }
        if (authResult == null) {
            authResult = getAuthenticationResult(request);
            if (!authResult.isAuthenticated()) {
                if (session != null) {
                    session.removeAttribute(AUTH_USER_SESSION_KEY);
                }
                m_rate_limited_log.log("JSON interface exception: " + authResult.m_message, EstTime.currentTimeMillis());
            } else {
                if (session != null) {
                    //Cache the authResult in session so we dont authenticate again.
                    session.setAttribute(AUTH_USER_SESSION_KEY, authResult);
                }
            }
        }
        return authResult;
    }
854207
@Override
    @FFDCIgnore({ com.ibm.ws.security.authentication.AuthenticationException.class })
    public AuthenticationResult authenticate(HttpServletRequest request,
                                             HttpServletResponse response,
                                             HashMap<String, Object> props) throws Exception {
        WebRequest webRequest = new WebRequestImpl(request, response, ((WebAppConfig) props.get("webAppConfig")).getApplicationName(), null, (SecurityMetadata) props.get("securityMetadata"), null, (WebAppSecurityConfig) props.get("webAppSecurityConfig"));
        JaspiRequest jaspiRequest = new JaspiRequest(webRequest, (WebAppConfig) props.get("webAppConfig"));
        AuthenticationResult result = null;
        AuthConfigProvider provider = getAuthConfigProvider(jaspiRequest.getAppContext());
        if (provider != null) {
            try {
                if (jaspiRequest.getWebSecurityContext() != null) {
                    JaspiAuthContext jaspiContext = getJaspiAuthContext(jaspiRequest, provider);
                    webRequest.getWebSecurityContext().setJaspiAuthContext(jaspiContext);
                }
                result = authenticate(new Subject(),
                                      getJaspiAuthType(jaspiRequest),
                                      jaspiRequest,
                                      provider);

            } catch (AuthenticationException e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Internal error during JASPI authentication", e);
                result = new AuthenticationResult(AuthResult.FAILURE, e.getMessage());

            }
        } else {
            result = new AuthenticationResult(AuthResult.CONTINUE, "No JASPI provider found for request: " + request.getRequestURI());

        }
        return result;
    }
1253446
def authenticate(self):
        
        if request.headers.get('Authorization') or request.args.get('access_token'):
            realm = 'Bearer realm="%s", error="invalid_token"' % __package__
        else:
            realm = 'Bearer realm="%s"' % __package__
        resp = Response(None, 401, {'WWW-Authenticate': realm})
        abort(401, description='Please provide proper credentials', response=resp)
121936
public Principal authenticate(String username, char password[]) 
    throws NamingException
	{
		DirContext ctx = null;
		try
		{
			String userDN = toDN(username);
			ctx = initContext(userDN, password);

			return new X500Principal(userDN);
		}
		finally
		{
			if(ctx != null)
				try{ ctx.close(); } catch(Exception e){e.printStackTrace();}
		}
	}
1084086
private static Credential authenticate(String userId, SessionConfiguration config) throws Exception {
        OAuth2Credentials oAuth2Credentials = createOAuth2Credentials(config);

        // First try to load an existing Credential. If that credential is null, authenticate the user.
        Credential credential = oAuth2Credentials.loadCredential(userId);
        if (credential == null || credential.getAccessToken() == null) {
            // Send user to authorize your application.
            System.out.printf("Add the following redirect URI to your developer.uber.com application: %s%n",
                    oAuth2Credentials.getRedirectUri());
            System.out.println("Press Enter when done.");

            System.in.read();

            // Generate an authorization URL.
            String authorizationUrl = oAuth2Credentials.getAuthorizationUrl();
            System.out.printf("In your browser, navigate to: %s%n", authorizationUrl);
            System.out.println("Waiting for authentication...");

            // Wait for the authorization code.
            String authorizationCode = localServerReceiver.waitForCode();
            System.out.println("Authentication received.");

            // Authenticate the user with the authorization code.
            credential = oAuth2Credentials.authenticate(authorizationCode, userId);
        }
        localServerReceiver.stop();

        return credential;
    }
698331
private <T> void authenticateExecuteAndProcessResults(Supplier<String> authenticator, Function<String, CompletableFuture<T>> call,
                                                          final StreamObserver<T> streamObserver, RequestTag requestTag) {
        try {
            String delegationToken;
            delegationToken = authenticator.get();
            CompletableFuture<T> result = call.apply(delegationToken);
            result.whenComplete(
                    (value, ex) -> {
                        log.debug("result =  {}", value);
                        logAndUntrackRequestTag(requestTag);
                        if (ex != null) {
                            Throwable cause = Exceptions.unwrap(ex);
                            log.error("Controller api failed with error: ", ex);
                            String errorDescription = replyWithStackTraceOnError ? "controllerStackTrace=" + Throwables.getStackTraceAsString(ex) : cause.getMessage();
                            streamObserver.onError(Status.INTERNAL
                                    .withCause(cause)
                                    .withDescription(errorDescription)
                                    .asRuntimeException());
                        } else if (value != null) {
                            streamObserver.onNext(value);
                            streamObserver.onCompleted();
                        }
                    });
        } catch (Exception e) {
            log.error("Controller api failed with authenticator error");
            logAndUntrackRequestTag(requestTag);
            streamObserver.onError(Status.UNAUTHENTICATED
                    .withDescription("Authentication failed")
                    .asRuntimeException());
        }
    }
503536
@Override
    public AuthenticationResult authenticate(WebRequest webRequest) {
        AuthenticationResult authResult = handleTAI(webRequest, true);
        if ((authResult.getStatus() == AuthResult.CONTINUE) && continueAfterUnprotectedURI(webRequest)) {
            authResult = handleSSO(webRequest, null);
            if (authResult.getStatus() == AuthResult.CONTINUE) {
                webRequest.setCallAfterSSO(true);
                authResult = handleTAI(webRequest, false);
            }
        }

        return authResult;

    }
118912
public Principal authenticate(String username,
                                  Object credentials,
                                  HttpRequest request)
    {

    	synchronized(this)
    	{
    		long now = System.currentTimeMillis();
    		if (now - _lastHashPurge > _cacheTime || _cacheTime == 0)
    		{
    			super.clear();
    			_roles.clear();
    			_lastHashPurge = now;
    		}
    		Principal user = (Principal)super.get(username);
    		if (user == null)
    		{
    			loadUser(username);
    			user = (Principal)super.get(username);
    		}
    	}
        return super.authenticate(username, credentials, request);
    }
301267
func (c *Connection) Authenticate() (err error) {
	c.authLock.Lock()
	defer c.authLock.Unlock()
	return c.authenticate()
}
731900
public void authenticate(){
        if(fingerprintSecureCallback!=null){
            if(cryptoObject!=null){
                throw new RuntimeException("If you specify a CryptoObject you have to use FingerprintCallback");
            }
            cryptoObject = cipherHelper.getEncryptionCryptoObject();
            if(cryptoObject==null) {
                fingerprintSecureCallback.onNewFingerprintEnrolled(new FingerprintToken(cipherHelper));
            }
        }
        else if(fingerprintCallback==null){
            throw new RuntimeException("You must specify a callback.");
        }

        cancellationSignal = new CancellationSignal();
        if(fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints()) {
            fingerprintManager.authenticate(cryptoObject, cancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
                @Override
                public void onAuthenticationError(int errorCode, CharSequence errString) {
                    super.onAuthenticationError(errorCode, errString);
                    setStatus(R.drawable.fingerprint_error, fingerprintError, circleError);
                    handler.postDelayed(returnToScanning, delayAfterError);
                    if(fingerprintSecureCallback!=null){
                        fingerprintSecureCallback.onAuthenticationError(errorCode, errString.toString());
                    } else{
                        fingerprintCallback.onAuthenticationError(errorCode, errString.toString());
                    }
                }

                @Override
                public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                    super.onAuthenticationHelp(helpCode, helpString);
                    setStatus(R.drawable.fingerprint_error, fingerprintError, circleError);
                    handler.postDelayed(returnToScanning, delayAfterError);
                    if(fingerprintSecureCallback!=null){
                        fingerprintSecureCallback.onAuthenticationError(helpCode, helpString.toString());
                    } else{
                        fingerprintCallback.onAuthenticationError(helpCode, helpString.toString());
                    }
                }

                @Override
                public void onAuthenticationSucceeded(final FingerprintManager.AuthenticationResult result) {
                    super.onAuthenticationSucceeded(result);
                    handler.removeCallbacks(returnToScanning);
                    setStatus(R.drawable.fingerprint_success, fingerprintSuccess, circleSuccess);
                    if(fingerprintSecureCallback!=null){
                        fingerprintSecureCallback.onAuthenticationSucceeded();
                    }
                    else{
                        fingerprintCallback.onAuthenticationSucceeded();
                    }
                    tryCounter = 0;
                }

                @Override
                public void onAuthenticationFailed() {
                    super.onAuthenticationFailed();
                    setStatus(R.drawable.fingerprint_error, fingerprintError, circleError);
                    handler.postDelayed(returnToScanning, delayAfterError);
                    handler.postDelayed(checkForLimit, delayAfterError);
                    if(fingerprintSecureCallback!=null){
                        fingerprintSecureCallback.onAuthenticationFailed();
                    }
                    else{
                        fingerprintCallback.onAuthenticationFailed();
                    }
                }
            }, null);
        }
        else{
            Log.e(TAG, "Fingerprint scanner not detected or no fingerprint enrolled. Use FingerprintView#isAvailable(Context) before.");
        }
    }
326974
func (sa *staticAuthenticator) Authenticate(user string, pass string) bool {
	password, found := sa.credentials[user]
	if !found {
		return false
	}
	return pass == password
}
1317483
public void authenticate(String authCode) {
        URL url = null;
        try {
            url = new URL(this.tokenURL);
        } 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 urlParameters = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s",
            authCode, this.clientID, this.clientSecret);

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

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

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.accessToken = jsonObject.get("access_token").asString();
        this.refreshToken = jsonObject.get("refresh_token").asString();
        this.lastRefresh = System.currentTimeMillis();
        this.expires = jsonObject.get("expires_in").asLong() * 1000;
    }