@Test public void testGetNullAuthModule() { Authenticator authenticator = new Authenticator(SIMPLE_URL); assertNull(authenticator.get(SIMPLE_MODULE_NAME)); }
private String getDecision( String xacmlRequest, EntitlementThriftClient.Client client, Authenticator authenticator) throws Exception { try { return client.getDecision(xacmlRequest, authenticator.getSessionId(false)); } catch (TException e) { if (log.isDebugEnabled()) { log.debug("Thrift entitlement exception : ", e); } throw new EntitlementProxyException( "Error while getting decision from PDP using ThriftEntitlementServiceClient", e); } catch (EntitlementException e) { if (log.isDebugEnabled()) { log.debug("Exception occurred : ", e); } try { return client.getDecision(xacmlRequest, authenticator.getSessionId(true)); } catch (Exception e1) { if (log.isDebugEnabled()) { log.debug("Exception occurred : ", e1); } throw new EntitlementProxyException( "Error while attempting to re-authenticate the Thrift client in ", e1); } } }
@Test public void testAddSimpleAuthenticator() { Authenticator authenticator = new Authenticator(SIMPLE_URL); AuthenticationModule simpleAuthModule = authenticator.auth(SIMPLE_MODULE_NAME, new AuthenticationConfig()); assertNotNull(simpleAuthModule); }
@Test public void testAddAndGetSimpleAuthenticator() { Authenticator authenticator = new Authenticator(SIMPLE_URL); AuthenticationModule simpleAuthModule = authenticator.auth(SIMPLE_MODULE_NAME, new AuthenticationConfig()); assertEquals(simpleAuthModule, authenticator.get(SIMPLE_MODULE_NAME)); authenticator.remove(SIMPLE_MODULE_NAME); assertNull(authenticator.get(SIMPLE_MODULE_NAME)); }
public void notify(Packet packet) { Log.trace("Register handling " + packet.toString()); String type = packet.getType(); Packet query = packet.getFirstChild("query"); if (type.equals("get")) { required.setSession(packet.getSession()); required.setID(packet.getID()); MessageHandler.deliverPacket(required); return; } else if (type.equals("set")) { // type == set String username = query.getChildValue("username"); User user = userIndex.getUser(username); if (user != null) { // user exists if (packet.getSession().getStatus() != Session.AUTHENTICATED || !username.equals(packet.getSession().getJID().getUser())) { Packet iq = new Packet("iq"); iq.setSession(packet.getSession()); iq.setID(packet.getID()); ErrorTool.setError(iq, 401, "User account already exists"); MessageHandler.deliverPacket(iq); return; } } else { user = userIndex.addUser(username); } user.setPassword(query.getChildValue("password")); user.setHash(query.getChildValue("hash")); user.setSequence(query.getChildValue("sequence")); user.setToken(query.getChildValue("token")); if (user.getHash() == null || user.getSequence() == null || user.getToken() == null) { if (user.getPassword() != null) { user.setToken(Authenticator.randomToken()); user.setSequence("99"); user.setHash( auth.getZeroKHash(100, user.getToken().getBytes(), user.getPassword().getBytes())); } } else { user.setSequence(Integer.toString(Integer.parseInt(user.getSequence()) - 1)); } Packet iq = new Packet("iq"); iq.setSession(packet.getSession()); iq.setID(packet.getID()); iq.setType("result"); // success MessageHandler.deliverPacket(iq); Log.trace( "Register successfully registered " + username + " with password " + query.getChildValue("password")); } else { Log.info("Register ignoring " + packet.toString()); } }
protected void ldapLogin() throws CLIException { if (ssoToken == null) { Authenticator auth = Authenticator.getInstance(); String bindUser = getAdminID(); ssoToken = auth.ldapLogin(getCommandManager(), bindUser, getAdminPassword()); } else { try { SSOTokenManager mgr = SSOTokenManager.getInstance(); mgr.validateToken(ssoToken); } catch (SSOException e) { throw new CLIException(e, ExitCodes.SESSION_EXPIRED); } } }
public static void main(String[] args) throws Exception { // assume NTLM is not supported when Kerberos is not available try { Class.forName("javax.security.auth.kerberos.KerberosPrincipal"); System.out.println("Kerberos is present, assuming NTLM is supported too"); return; } catch (ClassNotFoundException okay) { } // setup Authenticator Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user", "pass".toCharArray()); } }); // test combinations of authentication schemes test("Basic"); test("Digest"); test("Basic", "Digest"); test("Basic", "NTLM"); test("Digest", "NTLM"); test("Basic", "Digest", "NTLM"); // test NTLM only, this should fail with "401 Unauthorized" testNTLM(); System.out.println(); System.out.println("TEST PASSED"); }
@Override protected void doStart() throws Exception { // copy security init parameters ContextHandler.Context context = ContextHandler.getCurrentContext(); if (context != null) { Enumeration<String> names = context.getInitParameterNames(); while (names != null && names.hasMoreElements()) { String name = names.nextElement(); if (name.startsWith("org.eclipse.jetty.security.") && getInitParameter(name) == null) setInitParameter(name, context.getInitParameter(name)); } } // complicated resolution of login and identity service to handle // many different ways these can be constructed and injected. if (_loginService == null) { setLoginService(findLoginService()); if (_loginService != null) unmanage(_loginService); } if (_identityService == null) { if (_loginService != null) setIdentityService(_loginService.getIdentityService()); if (_identityService == null) setIdentityService(findIdentityService()); if (_identityService == null) { if (_realmName != null) { setIdentityService(new DefaultIdentityService()); manage(_identityService); } } else unmanage(_identityService); } if (_loginService != null) { if (_loginService.getIdentityService() == null) _loginService.setIdentityService(_identityService); else if (_loginService.getIdentityService() != _identityService) throw new IllegalStateException("LoginService has different IdentityService to " + this); } Authenticator.Factory authenticatorFactory = getAuthenticatorFactory(); if (_authenticator == null && authenticatorFactory != null && _identityService != null) setAuthenticator( authenticatorFactory.getAuthenticator( getServer(), ContextHandler.getCurrentContext(), this, _identityService, _loginService)); if (_authenticator != null) _authenticator.setConfiguration(this); else if (_realmName != null) { LOG.warn("No Authenticator for " + this); throw new IllegalStateException("No Authenticator"); } super.doStart(); }
@Test(expected = IllegalArgumentException.class) public void testAddAuthenticatorFailsWithUnsupportedType() { Authenticator authenticator = new Authenticator(SIMPLE_URL); AuthenticationConfig config = new AuthenticationConfig(); config.setAuthType( new AuthType() { @Override public String getName() { return "Bad type"; } }); AuthenticationModule simpleAuthModule = authenticator.auth(SIMPLE_MODULE_NAME, config); assertNotNull(simpleAuthModule); }
@Override public void init() throws Exception { Utils.validateNotEmpty(auth_url, "auth_url"); Utils.validateNotEmpty(auth_type, "auth_type"); Utils.validateNotEmpty(username, "username"); Utils.validateNotEmpty(password, "password"); Utils.validateNotEmpty(container, "container"); Authenticator authenticator = createAuthenticator(); authenticator.validateParams(); swiftClient = new SwiftClient(authenticator); // Authenticate now to record credential swiftClient.authenticate(); super.init(); }
public CompletionStage<Result> call(final Context ctx) { Authenticator authenticator = injector.instanceOf(configuration.value()); String username = authenticator.getUsername(ctx); if (username == null) { Result unauthorized = authenticator.onUnauthorized(ctx); return CompletableFuture.completedFuture(unauthorized); } else { try { ctx.request().setUsername(username); return delegate .call(ctx) .whenComplete((result, error) -> ctx.request().setUsername(null)); } catch (Exception e) { ctx.request().setUsername(null); throw e; } } }
public boolean userLogging(String userId, String password) { if (Authenticator.validate(userId, password)) { loggedUser = User.of(userId); gotoProfile(); return true; } else { return false; } }
@Test public void testAddAuthenticator() { Authenticator authenticator = new Authenticator(SIMPLE_URL); AuthenticationConfig config = new AuthenticationConfig(); config.setAuthType(AuthTypes.AG_SECURITY); config.setEnrollEndpoint("testEnroll"); config.setLoginEndpoint("testLogin"); config.setLogoutEndpoint("testLogout"); AuthenticationModule simpleAuthModule = authenticator.auth(SIMPLE_MODULE_NAME, config); assertEquals(simpleAuthModule, authenticator.get(SIMPLE_MODULE_NAME)); assertEquals("testEnroll", simpleAuthModule.getEnrollEndpoint()); assertEquals("testLogin", simpleAuthModule.getLoginEndpoint()); assertEquals("testLogout", simpleAuthModule.getLogoutEndpoint()); }
CommandResult authenticate(Mongo mongo, final MongoCredential credentials) { Authenticator authenticator; if (credentials.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) { authenticator = new NativeAuthenticator(mongo, credentials); } else if (credentials.getMechanism().equals(MongoCredential.GSSAPI_MECHANISM)) { authenticator = new GSSAPIAuthenticator(mongo, credentials); } else if (credentials.getMechanism().equals(MongoCredential.PLAIN_MECHANISM)) { authenticator = new PlainAuthenticator(mongo, credentials); } else if (credentials.getMechanism().equals(MongoCredential.MONGODB_X509_MECHANISM)) { authenticator = new X509Authenticator(mongo, credentials); } else { throw new IllegalArgumentException( "Unsupported authentication protocol: " + credentials.getMechanism()); } CommandResult res = authenticator.authenticate(); authenticatedDatabases.add(credentials.getSource()); return res; }
@Override public void doOperation() { consoleDisplayFactory.getNewConsoleDisplay("Enter Login Credentials").display(); consoleDisplayFactory.getNewConsoleDisplay("---------------------------").display(); consoleDisplayFactory.getNewConsoleDisplay("BookLibrary Number :").display(); String libraryNumber = inputReader.read(); consoleDisplayFactory.getNewConsoleDisplay("Password :").display(); String password = inputReader.read(); currentUser = authenticator.authenticate(libraryNumber, password); }
@Override public ContainerRequest filter(ContainerRequest request) { String path = request.getPath(); log.info("Filtering request path: " + path); // IMPORTANT!!! First, Acknowledge any pre-flight test from browsers for // this case before validating the headers (CORS stuff) if (request.getMethod().equals("OPTIONS")) { log.info("en Options?"); ResponseBuilder builder = null; String response = "OK"; builder = Response.status(Response.Status.OK).entity(response); throw new WebApplicationException(builder.build()); } // Then check is the service key exists and is valid. Authenticator demoAuthenticator = Authenticator.getInstance(); String serviceKey = request.getHeaderValue(HttpHeaderNames.SERVICE_KEY); if (!demoAuthenticator.isServiceKeyValid(serviceKey)) { ResponseBuilder builder = null; String response = "Invalid Service Key"; builder = Response.status(Response.Status.UNAUTHORIZED).entity(response); throw new WebApplicationException(builder.build()); } // For any pther methods besides login, the authToken must be verified if (!path.startsWith("auth/login")) { String authToken = request.getHeaderValue(HttpHeaderNames.AUTH_TOKEN); // if it isn't valid, just kick them out. if (!demoAuthenticator.isAuthTokenValid(serviceKey, authToken)) { ResponseBuilder builder = null; String response = "Authentication is need"; builder = Response.status(Response.Status.UNAUTHORIZED).entity(response); throw new WebApplicationException(builder.build()); } } // read(request); return request; }
public Connection newConnection(Address address, Authenticator authenticator) throws IOException { checkLive(); final ConnectionImpl connection = new ConnectionImpl(address, socketOptions, client.getSerializationService()); if (socketInterceptor != null) { socketInterceptor.onConnect(connection.getSocket()); } connection.init(); authenticator.auth(connection); return connection; }
public Result call(Context ctx) { try { Authenticator authenticator = configuration.value().newInstance(); String username = authenticator.getUsername(ctx); if (username == null) { return authenticator.onUnauthorized(ctx); } else { try { ctx.request().setUsername(username); return deleguate.call(ctx); } finally { ctx.request().setUsername(null); } } } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } }
void prepareRequest( String actionURI, String shellId, String messageId, HashMap<String, String> options) { // add SOAP headers List<Header> soapHeaders = getSOAPHeaders(actionURI, URI_RESOURCE_SHELL_CMD, shellId, messageId, options); Client proxy = ClientProxy.getClient(wsmanService); proxy.getRequestContext().put(Header.HEADER_LIST, soapHeaders); proxy.getRequestContext().put("SOAPAction", actionURI); transport.setupAuth(proxy); }
@Override public boolean checkCredentials(String username, String password) { int domainIndex = username.indexOf('@'); if (domainIndex != -1) { String domain = username.substring(domainIndex + 1); if (!"stackframe.com".equals(domain)) { // FIXME: Here is where we would dispatch to validate external users. logger.warning("Attempted log in of non-StackFrame resource. domain=" + domain); return false; } username = username.substring(0, domainIndex); } return stackFrameAuthenticator.checkCredentials(username, password); }
/** Is there an Individual associated with this user? */ private String getAssociatedIndividualUri() { UserAccount userAccount = LoginStatusBean.getCurrentUser(request); if (userAccount == null) { log.debug("Not logged in? Must be cancelling the password change"); return null; } List<String> uris = Authenticator.getInstance(request).getAssociatedIndividualUris(userAccount); if (uris.isEmpty()) { log.debug("'" + userAccount.getEmailAddress() + "' is not associated with an individual."); return null; } else { String uri = uris.get(0); log.debug("'" + userAccount.getEmailAddress() + "' is associated with an individual: " + uri); return uri; } }
public static void main(String[] args) throws Exception { MyAuthenticator auth = new MyAuthenticator(); Authenticator.setDefault(auth); try { server = new HttpServer(new AuthHeaderTest(), 1, 10, 0); System.out.println("Server: listening on port: " + server.getLocalPort()); client("http://localhost:" + server.getLocalPort() + "/d1/foo.html"); } catch (Exception e) { if (server != null) { server.terminate(); } throw e; } int f = auth.getCount(); if (f != 1) { except("Authenticator was called " + f + " times. Should be 1"); } server.terminate(); }
private int login(String id, String pass) { try { // connecting to Auth. server Socket socket1 = new Socket(Constants.AUTH_SERVER_HOST, Constants.AUTH_SERVER_PORT); in1 = new DataInputStream(socket1.getInputStream()); out1 = new DataOutputStream(socket1.getOutputStream()); // out.writeInt(1); // byte[] byteID=id.getBytes(); out1.writeUTF(id); // String reply=in.readUTF(); // System.out.println(reply); // out.writeUTF(pass); // reply=in.readUTF(); // System.out.println(reply); // receiving the session key msg int sessionKeyByteSize = in1.readInt(); byte[] sessionKeyByte = new byte[sessionKeyByteSize]; in1.readFully(sessionKeyByte); // obtaining the session key tgsSessionKey = EncryptionManager.decrypt(sessionKeyByte, EncryptionManager.generateSecretKey(pass)); // receiving the tgs ticket msg int tgsTicketByteSize = in1.readInt(); byte[] tgsTicketByte = new byte[tgsTicketByteSize]; in1.readFully(tgsTicketByte); // at this point client needs to communicate with TGS , sending the ticket and a new // authenticator // establishing the connection with TGS Socket socket2 = new Socket(Constants.TG_SERVER_HOST, Constants.TGS_PORT); in2 = new DataInputStream(socket2.getInputStream()); out2 = new DataOutputStream(socket2.getOutputStream()); // forwarding the tgs ticket to tgs server out2.writeInt(tgsTicketByteSize); out2.write(tgsTicketByte); // generating and sending an authenticator to send to tgs server Authenticator authenticator = new Authenticator(id, EncryptionManager.generateTimeStamp().getTime()); out2.writeInt( EncryptionManager.encrypt( authenticator.toString(), EncryptionManager.generateSecretKey(tgsSessionKey)) .length); out2.write( EncryptionManager.encrypt( authenticator.toString(), EncryptionManager.generateSecretKey(tgsSessionKey))); // receiving the authentication code( -1 for unvalidity and 1 for validity) int clientAuthValidityCode = in2.readInt(); if (clientAuthValidityCode == -1) { // client is not authenticated return -1; } else if (clientAuthValidityCode == 1) { // System.out.println("The user is authenticated by TGS "); // receiving Service server ticket int clientServerTicketByteSize = in2.readInt(); byte[] clientServerTicketByte = new byte[clientServerTicketByteSize]; in2.readFully(clientServerTicketByte); // receiving client/server session key int clientServerSessionKeySize = in2.readInt(); byte[] clientServerSessionKeyByte = new byte[clientServerSessionKeySize]; in2.readFully(clientServerSessionKeyByte); // decrypting clientServerSessionKey String clientServerSessionKey = EncryptionManager.decrypt( clientServerSessionKeyByte, EncryptionManager.generateSecretKey(tgsSessionKey)); // stablishing connection with service serve Socket socket3 = new Socket(Constants.SERVICE_SERVER_HOST, Constants.SERVICE_SERVER_PORT); in3 = new DataInputStream(socket3.getInputStream()); out3 = new DataOutputStream(socket3.getOutputStream()); // forwarding the clientServerTicket to service server out3.writeInt(clientServerTicketByteSize); out3.write(clientServerTicketByte); Authenticator authenticator2 = new Authenticator(id, EncryptionManager.generateTimeStamp().getTime()); // sending a new authenticator encrypted in clientServerSessionKey to service server out3.writeInt( EncryptionManager.encrypt( authenticator2.toString(), EncryptionManager.generateSecretKey(clientServerSessionKey)) .length); out3.write( EncryptionManager.encrypt( authenticator2.toString(), EncryptionManager.generateSecretKey(clientServerSessionKey))); // The SS decrypts the ticket using its own secret key to retrieve the Client/Server Session // Key. // Using the sessions key, SS decrypts the Authenticator and sends the following message to // the // client to confirm its true identity and willingness to serve the client: // (the timestamp found in client's Authenticator plus 1, encrypted using the Client/Server // Session Key) // // receiving the confirmation from server and decrypting it using SS session key int clientResultSize = in3.readInt(); byte[] clientResult = new byte[clientResultSize]; in3.readFully(clientResult); // decrypting the result from SS long result = Long.valueOf( EncryptionManager.decrypt( clientResult, EncryptionManager.generateSecretKey(clientServerSessionKey))); if (result == authenticator2.getTimeStamp() + 1) { // isLoggedIn=true; System.out.println("Client ready to communicate with service server.."); return 1; } else if (result == authenticator2.getTimeStamp() - 1) { System.out.println("Client is not authenticated!"); return -1; } else { System.out.println("result:" + result); System.out.println("authenticator.getTimeStamp(): " + authenticator.getTimeStamp()); System.out.println("This is not gonna happen!"); } // closing all sockets socket1.close(); socket2.close(); } } catch (IOException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { return 0; // e.printStackTrace(); } return 1; }
@Override public IBinder onBind(Intent intent) { return mAuthenticator.getIBinder(); }
@Override public boolean isValid(Action<? extends Result> action) throws ActionException { return authenticator.isUserLoggedIn(); }
@Test public void shouldFailAuthenticatingAUserWithInvalidPassword() { Authenticator authenticator = new Authenticator(); assertEquals("guest", authenticator.isValid("111-1111", "askldjf").role()); }
@Test public void shouldAuthenticateLibrarian() { Authenticator authenticator = new Authenticator(); assertEquals("admin", authenticator.isValid("000-0000", "secret").role()); }
@Test public void shouldAuthenticateAUserWithValidLibraryNumberAndPassword() { Authenticator authenticator = new Authenticator(); assertEquals("user", authenticator.isValid("111-1111", "abcxyz").role()); }
private void configureProxyAuthentication() { if (System.getProperty("http.proxyUser") != null) { Authenticator.setDefault(new SystemPropertiesProxyAuthenticator()); } }
/** * Authenticate * * @throws Exception */ public void authenticate() throws Exception { credentials = authenticator.authenticate(); }