org.eclipse.jetty.util.security.Credential Java Examples

The following examples show how to use org.eclipse.jetty.util.security.Credential. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #2
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
private static SecurityHandler createSecurityHandler() {
    UserStore userStore = new UserStore();
    String user = "user";
    String pwd = "user123!";
    String[] roles = new String[] { "user" };
    userStore.addUser(user, Credential.getCredential(pwd), roles);

    HashLoginService l = new HashLoginService();
    l.setName("apimanrealm");
    l.setUserStore(userStore);

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #3
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
private SecurityHandler createSecurityHandler() {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);

    for (String [] userInfo : TestUsers.USERS) {
        String user = userInfo[0];
        String pwd = userInfo[1];
        String[] roles = new String[] { "apiuser" };
        if (user.startsWith("admin")) {
            roles = new String[] { "apiuser", "apiadmin"};
        }
        userStore.addUser(user, Credential.getCredential(pwd), roles);
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #4
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 * @throws Exception
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    // UserStore is now separate store entity and must be added to HashLoginService
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #5
Source File: LdapLoginModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * get the available information about the user
 * <p/>
 * for this LoginModule, the credential can be null which will result in a
 * binding ldap authentication scenario
 * <p/>
 * roles are also an optional concept if required
 *
 * @param username
 * @return the userinfo for the username
 * @throws Exception
 */
@Override
public UserInfo getUserInfo(String username) throws Exception
{
  LdapEntry entry = getEntryWithCredential(username);

  if (entry == null)
  {
    return null;
  }

  String pwdCredential = getUserCredential(entry);
  pwdCredential = convertCredentialLdapToJetty(pwdCredential);
  Credential credential = Credential.getCredential(pwdCredential);
  List<String> roles = getUserRoles(username, entry.getDn());

  return new UserInfo(username, credential, roles);
}
 
Example #6
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 6 votes vote down vote up
private static SecurityHandler basicAuth(String username, String password, String realm) {
    HashLoginService loginService = new HashLoginService();
    loginService.putUser(username, Credential.getCredential(password), new String[]{"user"});
    loginService.setName(realm);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__DIGEST_AUTH);
    constraint.setRoles(new String[]{"user"});
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("realm");
    csh.addConstraintMapping(constraintMapping);
    csh.setLoginService(loginService);
    return csh;
}
 
Example #7
Source File: HttpServer.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
private void loadUsers() throws ParseException
{
    if (config.users != null)
    {            
        for (String userSpec: config.users)
        {
            String[] tokens = userSpec.split(":|,");
            if (tokens.length < 2)
                throw new ParseException("Invalid user spec: " + userSpec, 0);
            String username = tokens[0].trim();
            String password = tokens[1].trim();
            String[] roles = new String[tokens.length-2];
            for (int i = 0; i < roles.length; i++)
                roles[i] = tokens[i+2].trim();
            loginService.putUser(username, Credential.getCredential(password), roles);
        }
    }
}
 
Example #8
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Enables basic HTTP authentication on the server.
 */
public HttpService basicAuthentication(String username, String password) {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    userStore.addUser(username, Credential.getCredential(password), new String[]{"user"});
    l.setUserStore(userStore);
    l.setName("test-realm");

    Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, "user");
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("test-realm");
    csh.addConstraintMapping(constraintMapping);
    csh.setLoginService(l);

    this.securityHandler = Optional.of(csh);

    return this;
}
 
Example #9
Source File: MongoLoginService.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private User lookupUser(String username, Credential credential) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException {
    User user = userStore.readUser(userStore.searchUser(username));
    String hashedPassword = SecurityUtilities.hashPassword(credential.toString(), user.getSalt());
    if (hashedPassword.equals(user.getPassword())) {
        return user;
    } else {
        return null;
    }
}
 
Example #10
Source File: DigestAuthSupplierJettyTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() {
    server = new Server(PORT);

    HashLoginService loginService = new HashLoginService();
    loginService.setName("My Realm");
    UserStore userStore = new UserStore();
    String[] roles = new String[] {"user"};
    userStore.addUser(USER, Credential.getCredential(PWD), roles);
    loginService.setUserStore(userStore);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__DIGEST_AUTH);
    constraint.setRoles(roles);
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new DigestAuthenticator());
    csh.addConstraintMapping(cm);
    csh.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setSecurityHandler(csh);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new TestServlet()), "/*");

    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: LdapLoginModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * binding authentication check
 * This method of authentication works only if the user branch of the DIT (ldap tree)
 * has an ACI (access control instruction) that allow the access to any user or at least
 * for the user that logs in.
 *
 * @param username
 * @param password
 * @return true always
 * @throws LoginException
 */
public boolean bindingLogin(String username, Object password) throws Exception {
  if (StringUtils.isBlank(_userObjectClass)|| StringUtils.isBlank(_userIdAttribute)
      || StringUtils.isBlank(_userBaseDn)){
    LOG.error("Failed to get user because at least one of the following is null : " +
        "[_userObjectClass, _userIdAttribute, _userBaseDn ]");
    return false;
  }

  LdapEntry userEntry = authenticate(username, password);
  if (userEntry == null) {
    return false;
  }
  // If authenticated by LDAP server, the returned LdapEntry contains full DN of the user
  String userDn = userEntry.getDn();

  if(userDn == null){
    // This shouldn't happen if LDAP server is configured properly.
    LOG.error("userDn is found null for the user {}", username);
    return false;
  }

  List<String> roles = getUserRoles(username, userDn);
  //Authentication already succeeded. We won't store user password so passing empty credential
  UserInfo userInfo = new UserInfo(username, Credential.getCredential(""), roles);
  JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
  jaasUserInfo.fetchRoles();
  setCurrentUser(jaasUserInfo);
  setAuthenticated(true);

  return true;
}
 
Example #12
Source File: BaleenWebApi.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void configureServer(Server server, WebAuthConfig authConfig, Handler servletHandler)
    throws BaleenException {
  Handler serverHandler;

  if (authConfig == null || authConfig.getType() == AuthType.NONE) {
    LOGGER.warn("No security applied to API");
    // No security
    serverHandler = servletHandler;
  } else if (authConfig.getType() == AuthType.BASIC) {
    // Basic authentication
    LOGGER.info("Using Basic HTTP authentication for API");

    HashLoginService loginService = new HashLoginService(authConfig.getName());

    UserStore userStore = new UserStore();
    for (WebUser user : authConfig.getUsers()) {
      Credential credential = Credential.getCredential(user.getPassword());
      userStore.addUser(user.getUsername(), credential, user.getRolesAsArray());
    }
    loginService.setUserStore(userStore);
    server.addBean(loginService);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

    securityHandler.setHandler(servletHandler);
    securityHandler.setConstraintMappings(constraintMappings);
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setLoginService(loginService);

    serverHandler = securityHandler;
  } else {
    throw new InvalidParameterException("Configuration of authentication failed");
  }

  server.setHandler(serverHandler);
}
 
Example #13
Source File: SecurityServiceLoginService.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected UserIdentity loadUser(String username) {
    User user = securityService.getUser(username);
    if(user != null) {
        String password = (credentialType == CredentialType.BASIC) ? user.getBasicPassword() : user.getDigestPassword();
        List<String> roles = user.getRoles();
        return putUser(username, Credential.getCredential(password), roles.toArray(new String[roles.size()]));
    }
    return null;
}
 
Example #14
Source File: MongoLoginService.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private UserIdentity createUserIdentity(String username, Credential credential) {
    Principal userPrincipal = new AbstractLoginService.UserPrincipal(username, credential);
    Subject subject = new Subject();
    subject.getPrincipals().add(userPrincipal);
    subject.getPrivateCredentials().add(credential);
    subject.setReadOnly();
    return identityService.newUserIdentity(subject, userPrincipal, new String[]{"user"});
}
 
Example #15
Source File: LdapLoginModule.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/**
 * Init LoginModule.
 * Called once by JAAS after new instance is created.
 *
 * @param subject
 * @param callbackHandler
 * @param sharedState
 * @param options
 */
@Override
public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map<String,?> sharedState,
                       Map<String,?> options)
{
  super.initialize(subject, callbackHandler, sharedState, options);
  LOG.debug("Initializing Ldap configuration");

  _hostname = (String) options.get("hostname");
  _port = Integer.parseInt((String) options.get("port"));
  _bindDn = (String) options.get("bindDn");
  _bindPassword = (String) options.get("bindPassword");
  _userBaseDn = (String) options.get("userBaseDn");
  _roleBaseDn = (String) options.get("roleBaseDn");

  if (options.containsKey("forceBindingLogin")) {
    _forceBindingLogin = Boolean.parseBoolean((String) options.get("forceBindingLogin"));
  }

  if (options.containsKey("useLdaps")) {
    _useLdaps = Boolean.parseBoolean((String) options.get("useLdaps"));
  }

  if (options.containsKey("useStartTLS")) {
    _useStarttls = Boolean.parseBoolean((String) options.get("useStartTLS"));
  }

  _userObjectClass = getOption(options, "userObjectClass", _userObjectClass);
  _userRdnAttribute = getOption(options, "userRdnAttribute", _userRdnAttribute); //depricated
  _userIdAttribute = getOption(options, "userIdAttribute", _userIdAttribute);
  _userPasswordAttribute = getOption(options, "userPasswordAttribute", _userPasswordAttribute);
  _roleObjectClass = getOption(options, "roleObjectClass", _roleObjectClass);
  _roleMemberAttribute = getOption(options, "roleMemberAttribute", _roleMemberAttribute);
  _roleNameAttribute = getOption(options, "roleNameAttribute", _roleNameAttribute);
  _userFilter = getOption(options, "userFilter", _userFilter);
  _roleFilter = getOption(options, "roleFilter", _roleFilter);

  if (Configuration.FileRef.isValueMyRef(_bindPassword)) {
    Configuration.FileRef fileRef = new Configuration.FileRef(_bindPassword);
    _bindPassword = fileRef.getValue();
    if (_bindPassword != null) {
      _bindPassword = _bindPassword.trim();
    }
  }

  // Setup environment. If both useLdaps and useStartTLS are set to true, apply useStartTLS
  String ldapUrl;
  if (_useStarttls){
    ldapUrl = String.format("ldap://%s:%s", _hostname, _port);
  } else {
    ldapUrl = String.format("%s://%s:%s", _useLdaps ? "ldaps" : "ldap", _hostname, _port);
  }
  LOG.info("Accessing LDAP Server: {} startTLS: {}", ldapUrl, _useStarttls);
  connConfig = new ConnectionConfig(ldapUrl);
  connConfig.setUseStartTLS(_useStarttls);
  connConfig.setConnectionInitializer(
      new BindConnectionInitializer(_bindDn, new org.ldaptive.Credential(_bindPassword))
  );
  conn = DefaultConnectionFactory.getConnection(connConfig);
  try {
    conn.open();
  } catch (LdapException ex){
    LOG.error("Failed to establish connection to the LDAP server {}. {}", ldapUrl, ex);
    // We don't throw exception here because there might be multiple LDAP servers configured
  }
}
 
Example #16
Source File: LdapLoginModule.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/**
 * Perform authentication with given username and password.
 * Receive the result from Ldap server
 * @param username Username that user entered to login
 * @param password Password that user entered to login
 * @return LdapEntry which contains all user attributes
 */
private LdapEntry authenticate(String username,Object password)
{
  try {
    SearchDnResolver dnResolver = new SearchDnResolver(new DefaultConnectionFactory(connConfig));

    dnResolver.setBaseDn(_userBaseDn);
    dnResolver.setSubtreeSearch(true);
    String userFilter = buildFilter(_userFilter, _userObjectClass, _userIdAttribute);
    LOG.debug("Searching a user with filter {} where user is {}", userFilter, username);
    dnResolver.setUserFilter(userFilter);

    // Set Authenticator with username and password. It will return the user if username/password matches.
    BindAuthenticationHandler authHandler = new BindAuthenticationHandler(new DefaultConnectionFactory(connConfig));
    Authenticator auth = new Authenticator(dnResolver, authHandler);
    AuthenticationRequest authRequest = new AuthenticationRequest();
    authRequest.setUser(username);
    if (password instanceof char[]) {
      authRequest.setCredential(new org.ldaptive.Credential(new String((char[]) password)));
    } else if (password instanceof String){
      authRequest.setCredential(new org.ldaptive.Credential((String)password));
    } else {
      LOG.error("Unexpected type for password '{}'", (password != null) ? password.getClass() : "NULL");
      return null;
    }
    String[] userRoleAttribute = ReturnAttributes.ALL.value();
    authRequest.setReturnAttributes(userRoleAttribute);

    LOG.debug("Retrieved authenticator from factory: {}", auth);
    LOG.debug("Retrieved authentication request from factory: {}", authRequest);

    AuthenticationResponse response = auth.authenticate(authRequest);
    LOG.info("Found user?: {}", response.getResult());
    if (response.getResult()) {
      LdapEntry entry = response.getLdapEntry();
      return entry;
    } else {
      // User not found. Most likely username/password didn't match. Log the reason.
      LOG.error("Result code: {} - {}", response.getResultCode(), response.getMessage());
    }
  } catch (LdapException e) {
    LOG.warn(e.getMessage());
  }
  return null;
}
 
Example #17
Source File: InMemoryIdentityManager.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public void addUser(String userId, String password, String... roles) {
	UserStore userStore = new UserStore();
	userStore.addUser(userId, Credential.getCredential(password), roles);
	loginService.setUserStore(userStore);
}