Merge pull request #1488 from olamy/feature/1481

Add convenient method to add user to Realm
This commit is contained in:
Jan Bartel 2017-04-20 16:05:57 +10:00 committed by GitHub
commit 193c427a52
6 changed files with 214 additions and 76 deletions

View File

@ -22,6 +22,7 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.log.Log;
@ -49,11 +50,12 @@ public class HashLoginService extends AbstractLoginService
{
private static final Logger LOG = Log.getLogger(HashLoginService.class);
private PropertyUserStore _propertyUserStore;
private File _configFile;
private Resource _configResource;
private boolean hotReload = false; // default is not to reload
private UserStore _userStore;
private boolean _userStoreAutoCreate = false;
/* ------------------------------------------------------------ */
public HashLoginService()
@ -139,13 +141,21 @@ public class HashLoginService extends AbstractLoginService
this.hotReload = enable;
}
/**
* Configure the {@link UserStore} implementation to use.
* If none, for backward compat if none the {@link PropertyUserStore} will be used
* @param userStore the {@link UserStore} implementation to use
*/
public void setUserStore(UserStore userStore)
{
this._userStore = userStore;
}
/* ------------------------------------------------------------ */
@Override
protected String[] loadRoleInfo(UserPrincipal user)
{
UserIdentity id = _propertyUserStore.getUserIdentity(user.getName());
UserIdentity id = _userStore.getUserIdentity(user.getName());
if (id == null)
return null;
@ -154,21 +164,19 @@ public class HashLoginService extends AbstractLoginService
if (roles == null)
return null;
List<String> list = new ArrayList<>();
for (RolePrincipal r:roles)
list.add(r.getName());
List<String> list = roles.stream()
.map( rolePrincipal -> rolePrincipal.getName() )
.collect( Collectors.toList() );
return list.toArray(new String[roles.size()]);
}
/* ------------------------------------------------------------ */
@Override
protected UserPrincipal loadUserInfo(String userName)
{
UserIdentity id = _propertyUserStore.getUserIdentity(userName);
UserIdentity id = _userStore.getUserIdentity(userName);
if (id != null)
{
return (UserPrincipal)id.getUserPrincipal();
@ -187,16 +195,19 @@ public class HashLoginService extends AbstractLoginService
protected void doStart() throws Exception
{
super.doStart();
if (_propertyUserStore == null)
// can be null so we switch to previous behaviour using PropertyUserStore
if (_userStore == null)
{
if(LOG.isDebugEnabled())
LOG.debug("doStart: Starting new PropertyUserStore. PropertiesFile: " + _configFile + " hotReload: " + hotReload);
_propertyUserStore = new PropertyUserStore();
_propertyUserStore.setHotReload(hotReload);
_propertyUserStore.setConfigPath(_configFile);
_propertyUserStore.start();
PropertyUserStore propertyUserStore = new PropertyUserStore();
propertyUserStore.setHotReload(hotReload);
propertyUserStore.setConfigPath(_configFile);
propertyUserStore.start();
_userStore = propertyUserStore;
_userStoreAutoCreate = true;
}
}
@ -208,8 +219,8 @@ public class HashLoginService extends AbstractLoginService
protected void doStop() throws Exception
{
super.doStop();
if (_propertyUserStore != null)
_propertyUserStore.stop();
_propertyUserStore = null;
if (_userStore != null && _userStoreAutoCreate)
_userStore.stop();
_userStore = null;
}
}

View File

@ -18,12 +18,19 @@
package org.eclipse.jetty.security;
import org.eclipse.jetty.util.PathWatcher;
import org.eclipse.jetty.util.PathWatcher.PathWatchEvent;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.security.Credential;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@ -31,20 +38,6 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.security.auth.Subject;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.PathWatcher;
import org.eclipse.jetty.util.PathWatcher.PathWatchEvent;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.security.Credential;
/**
* PropertyUserStore
* <p>
@ -59,7 +52,7 @@ import org.eclipse.jetty.util.security.Credential;
*
* If DIGEST Authentication is used, the password must be in a recoverable format, either plain text or OBF:.
*/
public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.Listener
public class PropertyUserStore extends UserStore implements PathWatcher.Listener
{
private static final Logger LOG = Log.getLogger(PropertyUserStore.class);
@ -69,10 +62,7 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
protected PathWatcher pathWatcher;
protected boolean hotReload = false; // default is not to reload
protected IdentityService _identityService = new DefaultIdentityService();
protected boolean _firstLoad = true; // true if first load, false from that point on
protected final List<String> _knownUsers = new ArrayList<String>();
protected final Map<String, UserIdentity> _knownUserIdentities = new HashMap<String, UserIdentity>();
protected List<UserListener> _listeners;
/**
@ -145,12 +135,6 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
{
_configPath = configPath;
}
/* ------------------------------------------------------------ */
public UserIdentity getUserIdentity(String userName)
{
return _knownUserIdentities.get(userName);
}
/* ------------------------------------------------------------ */
/**
@ -199,8 +183,8 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
StringBuilder s = new StringBuilder();
s.append(this.getClass().getName());
s.append("[");
s.append("users.count=").append(this._knownUsers.size());
s.append("identityService=").append(this._identityService);
s.append("users.count=").append(this.getKnownUserIdentities().size());
s.append("identityService=").append(this.getIdentityService());
s.append("]");
return s.toString();
}
@ -220,7 +204,7 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
if (getConfigResource().exists())
properties.load(getConfigResource().getInputStream());
Set<String> known = new HashSet<String>();
Set<String> known = new HashSet<>();
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
@ -243,27 +227,12 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
}
known.add(username);
Credential credential = Credential.getCredential(credentials);
Principal userPrincipal = new AbstractLoginService.UserPrincipal(username,credential);
Subject subject = new Subject();
subject.getPrincipals().add(userPrincipal);
subject.getPrivateCredentials().add(credential);
if (roles != null)
{
for (String role : roleArray)
{
subject.getPrincipals().add(new AbstractLoginService.RolePrincipal(role));
}
}
subject.setReadOnly();
_knownUserIdentities.put(username,_identityService.newUserIdentity(subject,userPrincipal,roleArray));
addUser( username, credential, roleArray );
notifyUpdate(username,credential,roleArray);
}
}
final List<String> _knownUsers = new ArrayList<String>();
synchronized (_knownUsers)
{
/*
@ -277,7 +246,7 @@ public class PropertyUserStore extends AbstractLifeCycle implements PathWatcher.
String user = users.next();
if (!known.contains(user))
{
_knownUserIdentities.remove(user);
removeUser( user );
notifyRemove(user);
}
}

View File

@ -0,0 +1,76 @@
//
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.security;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.security.Credential;
import javax.security.auth.Subject;
import java.security.Principal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Base class to store User
*/
public class UserStore extends AbstractLifeCycle
{
private IdentityService _identityService = new DefaultIdentityService();
private final Map<String, UserIdentity> _knownUserIdentities = new ConcurrentHashMap<>();
public void addUser( String username, Credential credential, String[] roles)
{
Principal userPrincipal = new AbstractLoginService.UserPrincipal( username, credential);
Subject subject = new Subject();
subject.getPrincipals().add(userPrincipal);
subject.getPrivateCredentials().add(credential);
if (roles != null)
{
for (String role : roles)
{
subject.getPrincipals().add(new AbstractLoginService.RolePrincipal(role));
}
}
subject.setReadOnly();
_knownUserIdentities.put(username,_identityService.newUserIdentity(subject,userPrincipal,roles));
}
public void removeUser(String username)
{
_knownUserIdentities.remove(username);
}
public UserIdentity getUserIdentity(String userName)
{
return _knownUserIdentities.get(userName);
}
public IdentityService getIdentityService()
{
return _identityService;
}
public Map<String, UserIdentity> getKnownUserIdentities()
{
return _knownUserIdentities;
}
}

View File

@ -19,9 +19,14 @@
package org.eclipse.jetty.security;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.security.Credential;
/**
@ -31,9 +36,8 @@ import org.eclipse.jetty.util.security.Credential;
*/
public class TestLoginService extends AbstractLoginService
{
protected Map<String, UserPrincipal> _users = new HashMap<>();
protected Map<String, String[]> _roles = new HashMap<>();
UserStore userStore = new UserStore();
public TestLoginService(String name)
@ -43,9 +47,7 @@ public class TestLoginService extends AbstractLoginService
public void putUser (String username, Credential credential, String[] roles)
{
UserPrincipal userPrincipal = new UserPrincipal(username,credential);
_users.put(username, userPrincipal);
_roles.put(username, roles);
userStore.addUser( username, credential, roles );
}
/**
@ -54,7 +56,16 @@ public class TestLoginService extends AbstractLoginService
@Override
protected String[] loadRoleInfo(UserPrincipal user)
{
return _roles.get(user.getName());
UserIdentity userIdentity = userStore.getUserIdentity( user.getName() );
Set<RolePrincipal> roles = userIdentity.getSubject().getPrincipals( RolePrincipal.class);
if (roles == null)
return null;
List<String> list = new ArrayList<>();
for (RolePrincipal r:roles)
list.add(r.getName());
return list.toArray(new String[roles.size()]);
}
/**
@ -63,7 +74,8 @@ public class TestLoginService extends AbstractLoginService
@Override
protected UserPrincipal loadUserInfo(String username)
{
return _users.get(username);
UserIdentity userIdentity = userStore.getUserIdentity( username );
return userIdentity == null ? null : (UserPrincipal) userIdentity.getUserPrincipal();
}
}

View File

@ -0,0 +1,70 @@
//
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.security;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.security.Credential;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class UserStoreTest
{
UserStore userStore;
@Before
public void setup() {
userStore = new UserStore();
}
@Test
public void addUser()
{
this.userStore.addUser( "foo", Credential.getCredential( "beer" ), new String[]{"pub"} );
Assert.assertEquals(1, this.userStore.getKnownUserIdentities().size());
UserIdentity userIdentity = this.userStore.getUserIdentity( "foo" );
Assert.assertNotNull( userIdentity );
Assert.assertEquals( "foo", userIdentity.getUserPrincipal().getName() );
Set<AbstractLoginService.RolePrincipal>
roles = userIdentity.getSubject().getPrincipals( AbstractLoginService.RolePrincipal.class);
List<String> list = roles.stream()
.map( rolePrincipal -> rolePrincipal.getName() )
.collect( Collectors.toList() );
Assert.assertEquals(1, list.size());
Assert.assertEquals( "pub", list.get( 0 ) );
}
@Test
public void removeUser()
{
this.userStore.addUser( "foo", Credential.getCredential( "beer" ), new String[]{"pub"} );
Assert.assertEquals(1, this.userStore.getKnownUserIdentities().size());
UserIdentity userIdentity = this.userStore.getUserIdentity( "foo" );
Assert.assertNotNull( userIdentity );
Assert.assertEquals( "foo", userIdentity.getUserPrincipal().getName() );
userStore.removeUser( "foo" );
userIdentity = this.userStore.getUserIdentity( "foo" );
Assert.assertNull( userIdentity );
}
}

View File

@ -581,7 +581,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<version>2.20</version>
<configuration>
<argLine>@{argLine} -Dfile.encoding=UTF-8 -Duser.language=en -Duser.region=US -showversion -Xmx1g -Xms1g -XX:+PrintGCDetails</argLine>
<failIfNoTests>false</failIfNoTests>