/*
This method attempts to obtain the Principal of a user from a realm without having to
authenticate with a password or certificate. Not all realms support this, but we can use
reflection to peek into Realms that extend RealmBase.
766126
public static SipPrincipal impersonatePrincipal(String username, Realm realm) {
		Method getPrincipalMethod = null;
		Class clazz = realm.getClass();
		try {
			if(!(realm instanceof RealmBase)) {
				throw new RuntimeException("Only Realms extending RealmBase are supported. Report this error. Current realm class is " +
						realm.getClass().getCanonicalName());
			}
			while(getPrincipalMethod == null) {
				try {
					getPrincipalMethod = clazz.getDeclaredMethod("getPrincipal", String.class);
				} catch (NoSuchMethodException e) {
					log.warn("unexpected exception while impersonatePrincipal", e);
				}
				clazz = clazz.getSuperclass();
				if(clazz == null) break;
			}
			getPrincipalMethod.setAccessible(true);
			Principal principal =  (Principal) getPrincipalMethod.invoke(realm, username);
			return new CatalinaSipPrincipal(principal);
		} catch (Throwable t) {
			log.error("Could not impersonate user " + username, t);
		} finally {
			if(getPrincipalMethod != null) {
				getPrincipalMethod.setAccessible(false);
			}
		}
		return null;
		
	}
795215
@Override
	public PrincipalUser getUser(String username, String password) {
		requireNotDisposed();

		PrincipalUser result = _userService.findUserByUsername(username);
		String isPrivileged= _config.getValue(Property.IS_PRIVILEGED.getName(), Property.IS_PRIVILEGED.getDefaultValue());

		if(result == null){
			result = new PrincipalUser(_userService.findAdminUser(), username, username+"@gmail.com");
		}
                DAILY_USERS.put(username, System.currentTimeMillis());
                MONTHLY_USERS.put(username, System.currentTimeMillis());
                _monitorService.updateCounter(MonitorService.Counter.DAILY_USERS, DAILY_USERS.size(), new HashMap<>(0));
                _monitorService.updateCounter(MonitorService.Counter.MONTHLY_USERS, MONTHLY_USERS.size(), new HashMap<>(0));
		_monitorService.updateCounter(MonitorService.Counter.UNIQUE_USERS, _userService.getUniqueUserCount(), new HashMap<String, String>(0));

		try{
			Method method = PrincipalUser.class.getDeclaredMethod("setPrivileged", boolean.class);
			method.setAccessible(true);
			method.invoke(result, Boolean.parseBoolean(isPrivileged));

		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new SystemException("Failed to change privileged status.", e);
		}

		result = _userService.updateUser(result);
		return result;
	}
245789
public static Action unauthorized(final String realm) {
        return new Action(r -> {
            r.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            r.setStatus(HttpStatus.UNAUTHORIZED_401);
            return r;
        });
    }
1152389
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/id/{userId}")
    @Description("Returns the user having the given ID.")
    public PrincipalUserDto getUserById(@Context HttpServletRequest req,
        @PathParam("userId") final BigInteger userId) {
        if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) {
            throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
        }

        PrincipalUser remoteUser = validateAndGetOwner(req, null);
        PrincipalUser user = _uService.findUserByPrimaryKey(userId);

        if (user != null) {
            super.validateResourceAuthorization(req, user, remoteUser);
            return PrincipalUserDto.transformToDto(user);
        }
        throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
    }
553907
public PrincipalUser getRemoteUser(HttpServletRequest req) {
        requireArgument(req != null, "Request cannot be null.");
        
        if(req.getHeader(HttpHeaders.AUTHORIZATION) != null) {	
	        PrincipalUser result = null;
	        Object username = req.getAttribute(AuthFilter.USER_ATTRIBUTE_NAME);
	        
	        if (username != null) {
	            result = userService.findUserByUsername(String.class.cast(username));
	        }
	        return result;
        }
        
        return null;
    }
811293
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/username/{username}")
    @Description("Returns the user having the given username.")
    public PrincipalUserDto getUserByUsername(@Context HttpServletRequest req,
        @PathParam("username") final String userName) {

        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            System.out.println(headerName + ": " + headerValue);
        }

        if (userName == null || userName.isEmpty()) {
            throw new WebApplicationException("Username cannot be null or empty.", Status.BAD_REQUEST);
        }

        PrincipalUser remoteUser = validateAndGetOwner(req, null);
        PrincipalUser user = _uService.findUserByUsername(userName);

        if (user != null) {
            super.validateResourceAuthorization(req, user, remoteUser);
            return PrincipalUserDto.transformToDto(user);
        } else if (!remoteUser.isPrivileged()) {
            throw new WebApplicationException(Response.Status.FORBIDDEN.getReasonPhrase(), Response.Status.FORBIDDEN);
        } else {
            throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
        }
    }
802818
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));
    }
1367415
@Override
    public Function<Principal, Principal> getPrincipalMapper() {
        return p -> {
            final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(UserLdapCallbackHandler.class);
            LdapConnectionHandler ldapConnectionHandler = createLdapConnectionHandler();
            try {
                try {
                    SearchResult<LdapEntry> searchResult = userSearcherInjector.getValue().search(ldapConnectionHandler, p.getName());

                    return p instanceof RealmUser ? new MappedPrincipal(((RealmUser) p).getRealm(), searchResult.getResult().getSimpleName(), p.getName())
                            : new MappedPrincipal(searchResult.getResult().getSimpleName(), p.getName());
                } catch (IllegalStateException | IOException | NamingException e) {
                    SECURITY_LOGGER.trace("Unable to map principal.", e);
                    return p;
                }
            } finally {
                safeClose(ldapConnectionHandler);
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
            }
        };
    }
1270487
@Override
    public Principal getCallerPrincipal() {
        synchronized (this) {
            if ((state == PRE_CREATE) || (state == CREATING) || (!allowRollbackOnly))
                throw new IllegalStateException();
        }

        return super.getCallerPrincipal();

    }
187506
def _get_principal(self, app: FlaskUnchained) -> Principal:
        
        principal = Principal(app, use_sessions=False)
        principal.identity_loader(self._identity_loader)
        return principal
589422
@Produces
    @LoggedIn
    public String extractUsername() {

        final KeycloakPrincipal principal = (KeycloakPrincipal) httpServletRequest.getUserPrincipal();
        if (principal != null) {
            logger.debug("Running with Keycloak context");
            KeycloakSecurityContext kcSecurityContext = principal.getKeycloakSecurityContext();
            return kcSecurityContext.getToken().getPreferredUsername();
        }

        logger.debug("Running outside of Keycloak context");
        final String basicUsername = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(httpServletRequest)[0];
        if (! basicUsername.isEmpty()) {
            logger.debug("running HttpBasic auth");
            return basicUsername;
        }

        logger.debug("Running without any Auth context");
        return "admin"; // by default, we are admin!
    }
1075676
private SSLContext buildSSLContext(SecurityRealm realm) {
        if (realm.getAuthentication() == null || realm.getAuthentication().getTruststore() == null) {
            throw new IllegalArgumentException("No truststore configuration in security realm \"" + realm.getName() + "\".");
        }
        if (realm.getIdentities() == null || realm.getIdentities().getSsl() == null
                || realm.getIdentities().getSsl().getKeystore() == null) {
            throw new IllegalArgumentException("No keystore configuration in security realm \"" + realm.getName() + "\".");
        }

        SecurityRealm.Keystore keystore = realm.getIdentities().getSsl().getKeystore();
        SecurityRealm.Truststore truststore = realm.getAuthentication().getTruststore();

        String keystorePassword = keystore.getPassword();
        String keyPassword = keystore.getKeyPassword();

        // we'll reuse PID configuration for OCSP/CRL stuff
        return buildSSLContext(keystore.getPath(), keystore.getProvider(),
                keystorePassword, keyPassword,
                keystore.getAlias(),
                truststore.getPath(), truststore.getProvider(),
                truststore.getPassword(),
                configuration.isValidateCerts(), configuration.getCrlPath(),
                null, // "SHA1PRNG", "NativePRNGNonBlocking", ...
                configuration.isValidatePeerCerts(), configuration.isEnableCRLDP(), configuration.isEnableOCSP(),
                configuration.getOcspResponderURL(),
                configuration.getSslKeystoreProvider(),
                configuration.getSslTrustStoreProvider(),
                configuration.getSslProvider());
    }
1299055
private Iterator getInheritedPrincipals(IAuthorizationPrincipal principal)
            throws AuthorizationException {
        Iterator i = null;
        ArrayList<IAuthorizationPrincipal> al = new ArrayList<>(5);

        try {
            i = getGroupsForPrincipal(principal);
        } catch (GroupsException ge) {
            throw new AuthorizationException("Could not retrieve Groups for " + principal, ge);
        }

        while (i.hasNext()) {
            IEntityGroup group = (IEntityGroup) i.next();
            IAuthorizationPrincipal p = getPrincipalForGroup(group);
            al.add(p);
        }
        return al.iterator();
    }
1184471
@GET
    @Path("/getPrincipalClass")
    @RolesAllowed("Tester")
    public String getPrincipalClass(@Context SecurityContext sec) {
        Principal user = sec.getUserPrincipal();
        boolean isJsonWebToken = user instanceof JsonWebToken;
        return "isJsonWebToken:" + isJsonWebToken;
    }
168966
public static <T> Principal getPrincipalForCredential(final PropertyKey<T> key, final T value) {

		return getPrincipalForCredential(key, value, false);

	}
203041
function basicAuth(checker, realm) {

        realm = realm || 'Authorization Required';
        
        function unauthorized(res) {
            res.writeHead(401, {
                'WWW-Authenticate': 'Basic realm="' + realm + '"',
                'Content-Length': 13
            });
            res.end("Unauthorized\n");
        }

        function badRequest(res) {  
            res.writeHead(400, {
                "Content-Length": 12
            });
            res.end('Bad Request\n');
        }

        return function(req, res, next) {
            var authorization = req.headers.authorization;
            if (!authorization) return unauthorized(res);
            var parts = authorization.split(' ');
            var scheme = parts[0];
            var credentials = new Buffer(parts[1], 'base64').toString().split(':');
            if ('Basic' != scheme) return badRequest(res);
            checker(req, credentials[0], credentials[1], function (user) {
                if (!user) return unauthorized(res);
                req.remoteUser = user;
                next();
            });
        }
    }
1326576
@Override
    public Node getPrincipal() {
        if (principal == null) {
            principal = new LdapUser();
            LdapUser p = (LdapUser) principal;
            p.setDn(Configuration.getProperty(instanceName + ".principal").trim());
            p.setUid(getUidForDN(p.getDn()));
        }
        return principal;
    }