Java 类org.eclipse.jetty.server.UserIdentity 实例源码

项目:emodb    文件:AuthenticationResourceFilter.java   
/**
 * Certain aspects of the container, such as logging, need the authentication information to behave properly.
 * This method updates the request with the necessary objects to recognize the authenticated user.
 */
private void setJettyAuthentication(Subject subject) {
    // In unit test environments there may not be a current connection.  If any nulls are encountered
    // then, by definition, there is no container to update.
    HttpConnection connection = HttpConnection.getCurrentConnection();
    if (connection == null) {
        return;
    }
    Request jettyRequest = connection.getHttpChannel().getRequest();
    if (jettyRequest == null) {
        return;
    }

    // This cast down is safe; subject is always created with this type of principal
    PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal();
    UserIdentity identity = principal.toUserIdentity();

    jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity));
}
项目:drill    文件:DrillSpnegoLoginService.java   
@Override
public UserIdentity login(final String username, final Object credentials) {

  UserIdentity identity = null;
  try {
    identity = loggedInUgi.doAs(new PrivilegedExceptionAction<UserIdentity>() {
      @Override
      public UserIdentity run() {
        return spnegoLogin(credentials);
      }
    });
  } catch (Exception e) {
    logger.error("Failed to login using SPNEGO", e);
  }

  return identity;
}
项目:datacollector    文件:SSOAuthenticationUser.java   
@Override
public UserIdentity getUserIdentity() {
  return new UserIdentity() {
    @Override
    public Subject getSubject() {
      return new Subject(true, ImmutableSet.of(principal), Collections.emptySet(), Collections.emptySet());
    }

    @Override
    public Principal getUserPrincipal() {
      return principal;
    }

    @Override
    public boolean isUserInRole(String s, Scope scope) {
      return principal.getRoles().contains(s);
    }
  };
}
项目:datacollector    文件:ActivationAuthenticator.java   
@Override
public UserIdentity getUserIdentity() {
  final UserIdentity userIdentity = user.getUserIdentity();
  return new UserIdentity() {
    @Override
    public Subject getSubject() {
      return userIdentity.getSubject();
    }

    @Override
    public Principal getUserPrincipal() {
      return userIdentity.getUserPrincipal();
    }

    @Override
    public boolean isUserInRole(String role, Scope scope) {
      return ExpiredActivationUser.this.isUserInRole(scope, role);
    }
  };
}
项目:signalk-server-java    文件:SignalkLoginService.java   
@Override
public UserIdentity login(String username, Object creds) {

       UserIdentity user = null;


       // HERE IS THE HARDCODING
    boolean validUser = "admin".equals(username) && "s3cr3t".equals(creds);
    if (validUser) {
        Credential credential = (creds instanceof Credential)?(Credential)creds:Credential.getCredential(creds.toString());

        Principal userPrincipal = new MappedLoginService.KnownUser(username,credential);
        Subject subject = new Subject();
        subject.getPrincipals().add(userPrincipal);
        subject.getPrivateCredentials().add(creds);
        subject.setReadOnly();
        user=identityService.newUserIdentity(subject,userPrincipal, ACCESS_ROLE);
        users.put(user.getUserPrincipal().getName(), true);
    }

    return (user != null) ? user : null;
}
项目:CoVisor    文件:OVXLoginService.java   
@Override
public UserIdentity getUserIdentity() {
    // TODO: need to return the correct identity for this user.
    // Permitting specific logins for now with no passwords
    if (this.user.equals("tenant")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"user"});
    } else if (this.user.equals("ui")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"ui"});
    } else if (this.user.equals("admin")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"user", "admin", "ui"});
    } else {
        return null;
    }

}
项目:OpenVirteX    文件:OVXLoginService.java   
@Override
public UserIdentity getUserIdentity() {
    // TODO: need to return the correct identity for this user.
    // Permitting specific logins for now with no passwords
    if (this.user.equals("tenant")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"user"});
    } else if (this.user.equals("ui")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"ui"});
    } else if (this.user.equals("admin")) {
        return new DefaultUserIdentity(new Subject(), new JMXPrincipal(
                this.user), new String[] {"user", "admin", "ui"});
    } else {
        return null;
    }

}
项目:calcite-avatica    文件:SpnegoTestUtil.java   
@Override public void handle(String target, Request baseRequest, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
  Authentication auth = baseRequest.getAuthentication();
  if (Authentication.UNAUTHENTICATED == auth) {
    throw new AssertionError("Unauthenticated users should not reach here!");
  }

  baseRequest.setHandled(true);
  UserAuthentication userAuth = (UserAuthentication) auth;
  UserIdentity userIdentity = userAuth.getUserIdentity();
  Principal userPrincipal = userIdentity.getUserPrincipal();

  response.getWriter().print("OK " + userPrincipal.getName());
  response.setStatus(200);
}
项目:EDDI    文件:MongoLoginService.java   
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"});
}
项目:drill    文件:DrillRestLoginService.java   
@Override
public boolean validate(UserIdentity user) {
  // This is called for every request after authentication is complete to make sure the user is still valid.
  // Once a user is authenticated we assume that the user is still valid. This behavior is similar to ODBC/JDBC where
  // once a user is logged-in we don't recheck the credentials again in the same session.
  return true;
}
项目:drill    文件:DrillRestLoginService.java   
/**
 * This gets called whenever a session is invalidated (because of user logout) or timed out.
 * @param user - logged in UserIdentity
 */
@Override
public void logout(UserIdentity user) {
  // no-op
  if(logger.isTraceEnabled()) {
    logger.trace("Web user {} logged out.", user.getUserPrincipal().getName());
  }
}
项目:drill    文件:AbstractDrillLoginService.java   
@Override
public boolean validate(UserIdentity user) {
  // This is called for every request after authentication is complete to make sure the user is still valid.
  // Once a user is authenticated we assume that the user is still valid. This behavior is similar to ODBC/JDBC where
  // once a user is logged-in we don't recheck the credentials again in the same session.
  return true;
}
项目:drill    文件:AbstractDrillLoginService.java   
/**
 * This gets called whenever a session is invalidated (because of user logout) or timed out.
 * @param user
 */
@Override
public void logout(UserIdentity user) {
  final DrillUserPrincipal principal = (DrillUserPrincipal) user.getUserPrincipal();
  try {
    principal.close();
  } catch (final Exception e) {
    logger.error("Failure in logging out.", e);
  }
}
项目:drill    文件:DrillSpnegoAuthenticator.java   
public UserIdentity login(String username, Object password, ServletRequest request) {
  final UserIdentity user = super.login(username, password, request);

  if (user != null) {
    final HttpSession session = ((HttpServletRequest) request).getSession(true);
    final Authentication cached = new SessionAuthentication(this.getAuthMethod(), user, password);
    session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
  }

  return user;
}
项目:sql-layer    文件:HybridLoginService.java   
@Override
public UserIdentity login(String username, Object credentials) {
    UserIdentity inner = delegate.login(username, credentials);
    if (inner == null)
        return null;
    String userName = inner.getUserPrincipal().getName();
    int at = userName.indexOf('@');
    if (at >= 0) userName = userName.substring(0, at);
    User user = securityService.getUser(userName);
    if (user == null)
        return inner;
    else
        return new WrappedUserIdentity(inner, user);
}
项目:sql-layer    文件:SecurityServiceLoginService.java   
@Override
public UserIdentity login(String username, Object credentials) {
    long now = System.currentTimeMillis();
    if((now - lastCachePurge) > cacheMillis) {
        super._users.clear();
        lastCachePurge = now;
    }
    return super.login(username, credentials);
}
项目:sql-layer    文件:SecurityServiceLoginService.java   
@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;
}
项目:datacollector    文件:ActivationAuthenticator.java   
@Override
public boolean isUserInRole(UserIdentity.Scope scope, String role) {
  if (ALLOWED_ROLES.contains(role)) {
    return true;
  } else if (AuthzRole.ADMIN_ACTIVATION.equals(role) &&
             (user.isUserInRole(scope, AuthzRole.ADMIN) ||
              (user.isUserInRole(scope, AuthzRole.ADMIN_REMOTE)))) {
    return true;
  }
  return false;
}
项目:signalk-server-java    文件:SignalkLoginService.java   
@Override
public boolean validate(UserIdentity user) {
    if (users.containsKey(user.getUserPrincipal().getName()))
           return true;

       return false;    
}
项目:appengine-java-vm-runtime    文件:AppEngineAuthentication.java   
@Override
public void logout(UserIdentity user) {
  // Jetty calls this on every request -- even if user is null!
  if (user != null) {
    log.fine("Ignoring logout call for: " + user);
  }
}
项目:cxf-server    文件:SuCxfAuthenticator.java   
/**
 * Validate the request.
 * Any wsdl-query will get through.
 * Performs SPOCP query on anything else that's a UserAuthentication.
 *
 * @param request the request
 * @param response the response
 * @param mandatory mandatory or not
 * @return a Authentication
 * @throws ServerAuthException if something goes wrong.
 * @see SpnegoAuthenticator#validateRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse, boolean)
 */
public final Authentication validateRequest(final ServletRequest request,
                                            final ServletResponse response,
                                            final boolean mandatory) throws ServerAuthException {
  if (! (request instanceof HttpServletRequest)) {
    throw new IllegalStateException("Got a request of illegal type '" + request.getClass().getName() + "', should be '" + IllegalStateException.class.getName() + "'.");
  }

  if (isWsdlRequest(request)) {
    LOG.debug("WSDL request, sending deferred.");
    return _deferred;
  }

  Authentication authentication = doValidateRequest(request, response, mandatory);
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  String infoMessage = "Authentication response to '" + httpRequest.getRequestURI() + "':";

  if (authentication instanceof UserAuthentication) {
    UserAuthentication userAuthentication = (UserAuthentication) authentication;
    UserIdentity identity = userAuthentication.getUserIdentity();

    if (identity != null && identity.getUserPrincipal() != null) {

      String principalName = identity.getUserPrincipal().getName();
      infoMessage += " Negotiate: OK, user: " + principalName;
    } else {
      authentication = Authentication.UNAUTHENTICATED;
      infoMessage += " Negotiate: OK, user: UNKNOWN, " + authentication;
    }
  } else {
    infoMessage += " " + authentication;
  }


  LOG.info(infoMessage);
  return authentication;
}
项目:ofmeet-openfire-plugin    文件:OfMeetLoginService.java   
/**
 * Revoke authentication for the user
 *
 * @param identity the user to invalidate.
 */
@Override
public synchronized void logout( UserIdentity identity )
{
    tokenManager.revoke( identity.getUserPrincipal() );
}
项目:calcite-avatica    文件:PropertyBasedSpnegoLoginService.java   
@Override public UserIdentity login(String username, Object credentials) {
  String encodedAuthToken = (String) credentials;
  byte[] authToken = B64Code.decode(encodedAuthToken);

  GSSManager manager = GSSManager.getInstance();
  try {
    // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/jgss-features.html
    Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
    Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssName = manager.createName(serverPrincipal, null);
    // CALCITE-1922 Providing both OIDs is the bug in Jetty we're working around. By specifying
    // only one, we're requiring that clients *must* provide us the SPNEGO OID to authenticate
    // via Kerberos which is wrong. Best as I can tell, the SPNEGO OID is meant as another
    // layer of indirection (essentially is equivalent to setting the Kerberos OID).
    GSSCredential serverCreds = manager.createCredential(gssName,
        GSSCredential.INDEFINITE_LIFETIME, new Oid[] {krb5Oid, spnegoOid},
        GSSCredential.ACCEPT_ONLY);
    GSSContext gContext = manager.createContext(serverCreds);

    if (gContext == null) {
      LOG.debug("SpnegoUserRealm: failed to establish GSSContext");
    } else {
      while (!gContext.isEstablished()) {
        authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
      }
      if (gContext.isEstablished()) {
        String clientName = gContext.getSrcName().toString();
        String role = clientName.substring(clientName.indexOf('@') + 1);

        LOG.debug("SpnegoUserRealm: established a security context");
        LOG.debug("Client Principal is: {}", gContext.getSrcName());
        LOG.debug("Server Principal is: {}", gContext.getTargName());
        LOG.debug("Client Default Role: {}", role);

        SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken);

        Subject subject = new Subject();
        subject.getPrincipals().add(user);

        return _identityService.newUserIdentity(subject, user, new String[]{role});
      }
    }
  } catch (GSSException gsse) {
    LOG.warn("Caught GSSException trying to authenticate the client", gsse);
  }

  return null;
}
项目:sonar-scanner-maven    文件:ProxyAuthenticator.java   
/**
 * @see org.eclipse.jetty.security.Authenticator#validateRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse, boolean)
 */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
  HttpServletRequest request = (HttpServletRequest) req;
  HttpServletResponse response = (HttpServletResponse) res;
  String credentials = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());

  try {
    if (!mandatory)
      return new DeferredAuthentication(this);

    if (credentials != null) {
      int space = credentials.indexOf(' ');
      if (space > 0) {
        String method = credentials.substring(0, space);
        if ("basic".equalsIgnoreCase(method)) {
          credentials = credentials.substring(space + 1);
          credentials = B64Code.decode(credentials, StandardCharsets.ISO_8859_1);
          int i = credentials.indexOf(':');
          if (i > 0) {
            String username = credentials.substring(0, i);
            String password = credentials.substring(i + 1);

            UserIdentity user = login(username, password, request);
            if (user != null) {
              return new UserAuthentication(getAuthMethod(), user);
            }
          }
        }
      }
    }

    if (DeferredAuthentication.isDeferred(response))
      return Authentication.UNAUTHENTICATED;

    response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "basic realm=\"" + _loginService.getName() + '"');
    response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
    return Authentication.SEND_CONTINUE;
  } catch (IOException e) {
    throw new ServerAuthException(e);
  }
}
项目:EDDI    文件:MongoLoginService.java   
@Override
public boolean validate(UserIdentity userIdentity) {
    return false;  //TODO
}
项目:EDDI    文件:MongoLoginService.java   
@Override
public void logout(UserIdentity userIdentity) {
    //TODO
}
项目:drill    文件:DrillRestLoginService.java   
@Override
public UserIdentity login(String username, Object credentials) {
  if (!(credentials instanceof String)) {
    return null;
  }

  try {
    // Authenticate WebUser locally using UserAuthenticator. If WebServer is started that guarantees the PLAIN
    // mechanism is configured and authenticator is also available
    final AuthenticatorFactory plainFactory = drillbitContext.getAuthProvider()
        .getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
    final UserAuthenticator userAuthenticator = ((PlainFactory) plainFactory).getAuthenticator();

    // Authenticate the user with configured Authenticator
    userAuthenticator.authenticate(username, credentials.toString());

    logger.debug("WebUser {} is successfully authenticated", username);

    final SystemOptionManager sysOptions = drillbitContext.getOptionManager();

    final boolean isAdmin = ImpersonationUtil.hasAdminPrivileges(username,
            ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(sysOptions),
            ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(sysOptions));

    // Create the UserPrincipal corresponding to logged in user.
    final Principal userPrincipal = new DrillUserPrincipal(username, isAdmin);

    final Subject subject = new Subject();
    subject.getPrincipals().add(userPrincipal);
    subject.getPrivateCredentials().add(credentials);

    if (isAdmin) {
      subject.getPrincipals().addAll(DrillUserPrincipal.ADMIN_PRINCIPALS);
      return identityService.newUserIdentity(subject, userPrincipal, DrillUserPrincipal.ADMIN_USER_ROLES);
    } else {
      subject.getPrincipals().addAll(DrillUserPrincipal.NON_ADMIN_PRINCIPALS);
      return identityService.newUserIdentity(subject, userPrincipal, DrillUserPrincipal.NON_ADMIN_USER_ROLES);
    }
  } catch (final Exception e) {
    if (e instanceof UserAuthenticationException) {
      logger.debug("Authentication failed for WebUser '{}'", username, e);
    } else {
      logger.error("UnExpected failure occurred for WebUser {} during login.", username, e);
    }
    return null;
  }
}
项目:drill    文件:DrillSpnegoLoginService.java   
private UserIdentity spnegoLogin(Object credentials) {

    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();

    try {
      // Providing both OID's is required here. If we provide only one,
      // we're requiring that clients provide us the SPNEGO OID to authenticate via Kerberos.
      Oid[] knownOids = new Oid[2];
      knownOids[0] = new Oid("1.3.6.1.5.5.2"); // spnego
      knownOids[1] = new Oid("1.2.840.113554.1.2.2"); // kerberos

      GSSName gssName = manager.createName(spnegoConfig.getSpnegoPrincipal(), null);
      GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME,
          knownOids, GSSCredential.ACCEPT_ONLY);
      GSSContext gContext = manager.createContext(serverCreds);

      if (gContext == null) {
        logger.debug("SPNEGOUserRealm: failed to establish GSSContext");
      } else {
        while (!gContext.isEstablished()) {
          authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
        }

        if (gContext.isEstablished()) {
          String clientName = gContext.getSrcName().toString();
          String role = clientName.substring(clientName.indexOf(64) + 1);

          final SystemOptionManager sysOptions = drillContext.getOptionManager();
          final boolean isAdmin = ImpersonationUtil.hasAdminPrivileges(role,
              ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(sysOptions),
              ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(sysOptions));

          final Principal user = new DrillUserPrincipal(clientName, isAdmin);
          final Subject subject = new Subject();
          subject.getPrincipals().add(user);

          if (isAdmin) {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.ADMIN_USER_ROLES);
          } else {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.NON_ADMIN_USER_ROLES);
          }
        }
      }
    } catch (GSSException gsse) {
      logger.warn("Caught GSSException trying to authenticate the client", gsse);
    }
    return null;
  }
项目:drill    文件:TestSpnegoAuthentication.java   
/**
 * Validate successful {@link DrillSpnegoLoginService#login(String, Object)} when provided with client token for a
 * configured service principal.
 * @throws Exception
 */
@Test
public void testDrillSpnegoLoginService() throws Exception {

  // Create client subject using it's principal and keytab
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(spnegoHelper.CLIENT_PRINCIPAL,
          spnegoHelper.clientKeytab.getAbsoluteFile());

  // Generate a SPNEGO token for the peer SERVER_PRINCIPAL from this CLIENT_PRINCIPAL
  final String token = Subject.doAs(clientSubject, new PrivilegedExceptionAction<String>() {
    @Override
    public String run() throws Exception {

      final GSSManager gssManager = GSSManager.getInstance();
      GSSContext gssContext = null;
      try {
        final Oid oid = GSSUtil.GSS_SPNEGO_MECH_OID;
        final GSSName serviceName = gssManager.createName(spnegoHelper.SERVER_PRINCIPAL, GSSName.NT_USER_NAME, oid);

        gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
        gssContext.requestCredDeleg(true);
        gssContext.requestMutualAuth(true);

        byte[] outToken = new byte[0];
        outToken = gssContext.initSecContext(outToken, 0, outToken.length);
        return Base64.encodeBase64String(outToken);

      } finally {
        if (gssContext != null) {
          gssContext.dispose();
        }
      }
    }
  });

  // Create a DrillbitContext with service principal and keytab for DrillSpnegoLoginService
  final DrillConfig newConfig = new DrillConfig(DrillConfig.create()
      .withValue(ExecConstants.HTTP_AUTHENTICATION_MECHANISMS,
          ConfigValueFactory.fromIterable(Lists.newArrayList("spnego")))
      .withValue(ExecConstants.HTTP_SPNEGO_PRINCIPAL,
          ConfigValueFactory.fromAnyRef(spnegoHelper.SERVER_PRINCIPAL))
      .withValue(ExecConstants.HTTP_SPNEGO_KEYTAB,
          ConfigValueFactory.fromAnyRef(spnegoHelper.serverKeytab.toString())),
      false);


  final SystemOptionManager optionManager = Mockito.mock(SystemOptionManager.class);
  Mockito.when(optionManager.getOption(ExecConstants.ADMIN_USERS_VALIDATOR))
      .thenReturn(ExecConstants.ADMIN_USERS_VALIDATOR.DEFAULT_ADMIN_USERS);
  Mockito.when(optionManager.getOption(ExecConstants.ADMIN_USER_GROUPS_VALIDATOR))
      .thenReturn(ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.DEFAULT_ADMIN_USER_GROUPS);

  final DrillbitContext drillbitContext = Mockito.mock(DrillbitContext.class);
  Mockito.when(drillbitContext.getConfig()).thenReturn(newConfig);
  Mockito.when(drillbitContext.getOptionManager()).thenReturn(optionManager);

  final DrillSpnegoLoginService loginService = new DrillSpnegoLoginService(drillbitContext);

  // Authenticate the client using its SPNEGO token
  final UserIdentity user = loginService.login(null, token);

  // Validate the UserIdentity of authenticated client
  assertTrue(user != null);
  assertTrue(user.getUserPrincipal().getName().equals(spnegoHelper.CLIENT_PRINCIPAL));
  assertTrue(user.isUserInRole("authenticated", null));
}
项目:sql-layer    文件:HybridLoginService.java   
@Override
public boolean validate(UserIdentity user) {
    return delegate.validate(unwrap(user));
}
项目:sql-layer    文件:HybridLoginService.java   
@Override
public void logout(UserIdentity user) {
    delegate.logout(unwrap(user));
}
项目:sql-layer    文件:HybridLoginService.java   
public WrappedUserIdentity(UserIdentity delegate, User user) {
    this.delegate = delegate;
    this.user = user;
}
项目:sql-layer    文件:HybridLoginService.java   
@Override
public boolean isUserInRole(String role, UserIdentity.Scope scope) {
    return delegate.isUserInRole(role, scope) || user.hasRole(role);
}
项目:sql-layer    文件:HybridLoginService.java   
protected UserIdentity unwrap(UserIdentity user) {
    if (user instanceof WrappedUserIdentity)
        return ((WrappedUserIdentity)user).delegate;
    else
        return user;
}
项目:datacollector    文件:SSOAuthenticationUser.java   
@Override
public boolean isUserInRole(UserIdentity.Scope scope, String s) {
  return principal.getRoles().contains(s);
}
项目:datacollector    文件:FileUserGroupManager.java   
private void fetchUserAndGroupList() throws IOException {
  userList = new ArrayList<>();
  usersMap = new HashMap<>();
  groupList = new ArrayList<>();
  groupList.add(ALL_GROUP);
  if (hashLoginService != null) {
    Properties properties = new Properties();
    if ( hashLoginService.getResolvedConfigResource().exists()) {
      properties.load(hashLoginService.getResolvedConfigResource().getInputStream());
    }

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
      String userName = ((String)entry.getKey()).trim();
      UserJson user = new UserJson();
      user.setName(userName);
      List<String> roles = new ArrayList<>();
      List<String> groups = new ArrayList<>();
      groups.add(ALL_GROUP);
      UserIdentity userIdentity = hashLoginService.getUserIdentity(userName);
      Set<Principal> principals = userIdentity.getSubject().getPrincipals();
      for (Principal principal: principals) {
        if (principal instanceof AbstractLoginService.RolePrincipal) {
          if (principal.getName().startsWith(GROUP_PREFIX)) {
            String groupName = principal.getName().replace(GROUP_PREFIX, "");
            if (!groups.contains(groupName)) {
              groups.add(groupName);
            }
            if (!groupList.contains(groupName)) {
              groupList.add(groupName);
            }
          } else if (!roles.contains(principal.getName()) && !USER_ROLE.equals(principal.getName())) {
            roles.add(principal.getName());
          }
        }
      }
      user.setRoles(roles);
      user.setGroups(groups);
      userList.add(user);
      usersMap.put(userName, user);
    }
  }
}
项目:datacollector    文件:SdcHashLoginService.java   
public UserIdentity getUserIdentity(String name) {
  return _propertyUserStore.getUserIdentity(name);
}
项目:datacollector    文件:ProxyAuthenticator.java   
@Override
public UserIdentity login(String username, Object password, ServletRequest request) {
  return authenticator.login(username, password, request);
}
项目:datacollector    文件:TestActivationAuthenticator.java   
@Test
public void testExpiredActivationUser() {
  Authenticator auth = Mockito.mock(Authenticator.class);
  Activation activation = Mockito.mock(Activation.class);
  ActivationAuthenticator activationAuth = new ActivationAuthenticator(auth, activation);

  Authentication.User authUser = Mockito.mock(Authentication.User.class);
  Subject subject = new Subject();
  Principal principal = Mockito.mock(Principal.class);
  UserIdentity userIdentity = Mockito.mock(UserIdentity.class);
  Mockito.when(userIdentity.getSubject()).thenReturn(subject);
  Mockito.when(userIdentity.getUserPrincipal()).thenReturn(principal);
  Mockito.when(authUser.getUserIdentity()).thenReturn(userIdentity);
  Authentication.User expiredAuthUser = activationAuth.createExpiredActivationUser(authUser);

  Mockito.when(authUser.getAuthMethod()).thenReturn("foo");
  Assert.assertEquals("foo", expiredAuthUser.getAuthMethod());
  Mockito.verify(authUser, Mockito.times(1)).getAuthMethod();

  expiredAuthUser.logout();
  Mockito.verify(authUser, Mockito.times(1)).logout();

  // non admin user
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, "user"));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST_REMOTE));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN_ACTIVATION));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, "foo"));

  // admin user
  Mockito.when(authUser.isUserInRole(Mockito.eq(null), Mockito.eq(AuthzRole.ADMIN))).thenReturn(true);
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, "user"));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST_REMOTE));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN_ACTIVATION));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN_REMOTE));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, "foo"));

  // remote admin user
  Mockito.when(authUser.isUserInRole(Mockito.eq(null), Mockito.eq(AuthzRole.ADMIN_REMOTE))).thenReturn(true);
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, "user"));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.GUEST_REMOTE));
  Assert.assertTrue(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN_ACTIVATION));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, AuthzRole.ADMIN_REMOTE));
  Assert.assertFalse(expiredAuthUser.isUserInRole(null, "foo"));

  // verify UserIdentity.isUserInRole() delegation to ExpiredActivationUser.isUserInRole()
  expiredAuthUser = activationAuth.createExpiredActivationUser(authUser);
  expiredAuthUser = Mockito.spy(expiredAuthUser);
  userIdentity = expiredAuthUser.getUserIdentity();
  UserIdentity.Scope scope = Mockito.mock(UserIdentity.Scope.class);
  Assert.assertTrue(userIdentity.isUserInRole(AuthzRole.GUEST,scope));
  Mockito.verify(expiredAuthUser, Mockito.times(1)).isUserInRole(Mockito.eq(scope), Mockito.eq(AuthzRole.GUEST));
}
项目:Openfire    文件:OpenfireLoginService.java   
public void logout(UserIdentity identity)
{
    Log.debug("logout {}",identity);

    identities.remove(identity.getUserPrincipal().getName());
}