produces a JWT token based upon the jwt Configuration, and the security
credentials of the authenticated user that called this method. Returns
the token as JSON in the response.

@param response
@param jwtConfig
@throws IOException
325702
private void processTokenRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {

		String tokenString = new TokenBuilder().createTokenString(jwtConfig);
		addNoCacheHeaders(response);
		response.setStatus(200);

		if (tokenString == null) {
			return;
		}
		try {
			PrintWriter pw = response.getWriter();
			response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
			pw.write("{\"token\": \"" + tokenString + "\"}");
			pw.flush();
			pw.close();
		} catch (IOException e) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
			}
		}
	}
1325528
public ApiResponse<DynconfigGetConfigResponse> dynconfigGetConfigWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = dynconfigGetConfigValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<DynconfigGetConfigResponse>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }
1007401
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
    """"""
    assert user_id, "No user_id passed to generate_token()"
    assert isinstance(data, dict), "generate_token(data=) should be a dictionary"
    assert get_config().jwt_secret, "No JWT secret configured in pymacaron"

    if not issuer:
        issuer = get_config().jwt_issuer

    assert issuer, "No JWT issuer configured for pymacaron"

    if expire_in is None:
        expire_in = get_config().jwt_token_timeout

    if iat:
        epoch_now = iat
    else:
        epoch_now = to_epoch(timenow())
    epoch_end = epoch_now + expire_in

    data['iss'] = issuer
    data['sub'] = user_id
    data['aud'] = get_config().jwt_audience
    data['exp'] = epoch_end
    data['iat'] = epoch_now

    headers = {
        "typ": "JWT",
        "alg": "HS256",
        "iss": issuer,
    }

    log.debug("Encoding token with data %s and headers %s (secret:%s****)" % (data, headers, get_config().jwt_secret[0:8]))

    t = jwt.encode(
        data,
        get_config().jwt_secret,
        headers=headers,
    )

    if type(t) is bytes:
        t = t.decode("utf-8")

    return t
1338197
@Override
    protected int authenticated(final Request request, final Response response)
    {
        try
        {
            final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response);
            credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse()));
            credentialsCookie.setMaxAge(this.getMaxCookieAge());
        }
        catch(final GeneralSecurityException e)
        {
            this.log.error("Could not format credentials cookie", e);
        }
        
        // log.info("calling super.authenticated");
        // return super.authenticated(request, response);
        
        // Modified copy of Authenticator.authenticated
        if(this.log.isDebugEnabled())
        {
            this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request
                    .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme());
        }
        
        // Update the client info accordingly
        if(request.getClientInfo() != null)
        {
            request.getClientInfo().setAuthenticated(true);
        }
        
        // Clear previous challenge requests
        response.getChallengeRequests().clear();
        
        // Add the roles for the authenticated subject
        if(this.getEnroler() != null)
        {
            this.getEnroler().enrole(request.getClientInfo());
        }
        
        // Return STOP here works for login but not for subsequent requests that expect a response
        // return STOP;
        return Filter.CONTINUE;
    }
884802
public static String getJwt(JwtClaims claims) throws JoseException {
        String jwt;
        RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
                jwtConfig.getKey().getFilename(), (String)secretConfig.get(JWT_PRIVATE_KEY_PASSWORD), jwtConfig.getKey().getKeyName());

        // A JWT is a JWS and/or a JWE with JSON claims as the payload.
        // In this example it is a JWS nested inside a JWE
        // So we first create a JsonWebSignature object.
        JsonWebSignature jws = new JsonWebSignature();

        // The payload of the JWS is JSON content of the JWT Claims
        jws.setPayload(claims.toJson());

        // The JWT is signed using the sender's private key
        jws.setKey(privateKey);

        // Get provider from security config file, it should be two digit
        // And the provider id will set as prefix for keyid in the token header, for example: 05100
        // if there is no provider id, we use "00" for the default value
        String provider_id = "";
        if (jwtConfig.getProviderId() != null) {
            provider_id = jwtConfig.getProviderId();
            if (provider_id.length() == 1) {
                provider_id = "0" + provider_id;
            } else if (provider_id.length() > 2) {
                logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
                provider_id = provider_id.substring(0, 2);
            }
        }
        jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());

        // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

        // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
        // representation, which is a string consisting of three dot ('.') separated
        // base64url-encoded parts in the form Header.Payload.Signature
        jwt = jws.getCompactSerialization();
        return jwt;
    }
122422
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		String appid;
		if (requestURI.startsWith(SAML_ACTION)) {
			appid = Config.getRootAppIdentifier();
			if (requestURI.startsWith(SAML_ACTION + "/")) {
				String id = Utils.urlDecode(StringUtils.removeStart(requestURI, SAML_ACTION + "/"));
				if (!id.isEmpty()) {
					appid = id;
				} else {
					appid = Config.getRootAppIdentifier();
				}
			}
			try {
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				if (app != null) {
					SettingsBuilder builder = new SettingsBuilder();
					Map<String, Object> samlSettings;
					String idpMetaUrl = SecurityUtils.getSettingForApp(app, "security.saml.idp.metadata_url", "");

					if (StringUtils.isBlank(idpMetaUrl)) {
						samlSettings = getSAMLSettings(app);
					} else {
						samlSettings = parseRemoteXML(new URL(idpMetaUrl), request.getParameter("entityid"));
						samlSettings.putAll(getSAMLSettings(app)); // override IDP meta with config values
					}

					Saml2Settings settings = builder.fromValues(samlSettings).build();

					Auth auth = new Auth(settings, request, response);

					if (request.getParameter("SAMLResponse") != null) {
						auth.processResponse();
						if (auth.isAuthenticated()) {
							List<String> errors = auth.getErrors();
							if (errors.isEmpty()) {
								userAuth = getOrCreateUser(app, auth.getAttributes());
							} else {
								throw new AuthenticationServiceException(StringUtils.join(errors, "; "));
							}
						}
					} else {
						auth.login(settings.getSpAssertionConsumerServiceUrl().toString());
						return null; // redirect to IDP
					}
				}
			} catch (SettingsException ex) {
				LOG.error("Failed to authenticate app '{}' with SAML: {}", appid, ex.getMessage());
			} catch (Exception ex) {
				LOG.error(null, ex);
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
106466
private void loginForm(HttpServletResponse response) throws IOException {
        response.reset();
        response.addHeader("WWW-Authenticate",
                           "Basic realm=\"!!Fedora Repository Server\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        OutputStream out = response.getOutputStream();
        out.write("Fedora: 401 ".getBytes());
        out.flush();
        out.close();
    }
974094
public String signToken(AuthenticatedUser user) {
        Date expiry = new Date(System.currentTimeMillis() + this.jwtTimeout);
        JWTClaimsSet claimsSet = user.toClaimSet(this.jwtIssuer, expiry);
        SignedJWT jwt = this.signToken(claimsSet);
        return jwt.serialize();
    }
1214554
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(OAUTH2_ACTION)) {
			String authCode = request.getParameter("code");
			if (!StringUtils.isBlank(authCode)) {
				String appid = SecurityUtils.getAppidFromAuthRequest(request);
				String redirectURI = SecurityUtils.getRedirectUrl(request);
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.OAUTH2_PREFIX);
				String entity = Utils.formatMessage(PAYLOAD,
						authCode, Utils.urlEncode(redirectURI),
						URLEncoder.encode(SecurityUtils.getSettingForApp(app, "security.oauth.scope", ""), "UTF-8"),
						keys[0], keys[1]);

				String acceptHeader = SecurityUtils.getSettingForApp(app, "security.oauth.accept_header", "");
				HttpPost tokenPost = new HttpPost(SecurityUtils.getSettingForApp(app, "security.oauth.token_url", ""));
				tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
				tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
				if (!StringUtils.isBlank(acceptHeader)) {
					tokenPost.setHeader(HttpHeaders.ACCEPT, acceptHeader);
				}

				try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
					if (resp1 != null && resp1.getEntity() != null) {
						Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
						if (token != null && token.containsKey("access_token")) {
							userAuth = getOrCreateUser(app, (String) token.get("access_token"));
						}
						EntityUtils.consumeQuietly(resp1.getEntity());
					}
				}
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
1196938
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(TWITTER_ACTION)) {
			String verifier = request.getParameter("oauth_verifier");
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String denied = request.getParameter("denied");
			String redirectURI = SecurityUtils.getRedirectUrl(request) + (appid == null ? "" : "?appid=" + appid);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.TWITTER_PREFIX);
			if (denied != null) {
				throw new BadCredentialsException("Cancelled.");
			}

			if (verifier == null && stepOne(response, redirectURI, keys)) {
				return null;
			} else {
				userAuth = stepTwo(request, verifier, keys, app);
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
101383
public static JSONObject oauth(String apiKey, String secretKey, AipClientConfiguration config) {
        try {
            AipRequest request = new AipRequest();
            request.setUri(new URI(AipClientConst.OAUTH_URL));
            request.addBody("grant_type", "client_credentials");
            request.addBody("client_id", apiKey);
            request.addBody("client_secret", secretKey);
            request.setConfig(config);
            int statusCode = 500;
            AipResponse response = null;
            // add retry
            int cnt = 0;
            while (statusCode == 500 && cnt < 3) {
                response = AipHttpClient.post(request);
                statusCode = response.getStatus();
                cnt++;
            }
            String res = response.getBodyStr();
            if (res != null && !res.equals("")) {
                return new JSONObject(res);
            } else {
                return Util.getGeneralError(statusCode, "Server response code: " + statusCode);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return Util.getGeneralError(-1, "unknown error");
    }
209703
public static AuthenticationData createAuthenticationData(byte[] token) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            SibTr.entry(tc, CLASS_NAME + "createAuthenticationData", token);
        }
        AuthenticationData authData = new WSAuthenticationData();
        authData.set(AuthenticationData.TOKEN, token);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            SibTr.exit(tc, CLASS_NAME + "createAuthenticationData", authData);
        }
        return authData;
    }
117172
private void saveTokenFromResponse(Response response) {
        try {
            JSONObject responseJSON = ((ResponseImpl)response).getResponseJSON();

            String accessToken = responseJSON.getString("access_token");
            String idToken = responseJSON.getString("id_token");

            //save the tokens
            preferences.accessToken.set(accessToken);
            preferences.idToken.set(idToken);

            //save the user identity separately
            String[] idTokenData = idToken.split("\\.");
            byte[] decodedIdTokenData = Base64.decode(idTokenData[1], Base64.DEFAULT);
            String decodedIdTokenString = new String(decodedIdTokenData);
            JSONObject idTokenJSON = new JSONObject(decodedIdTokenString);

            if (idTokenJSON.has("imf.user")) {
                preferences.userIdentity.set(idTokenJSON.getJSONObject("imf.user"));
            }

            logger.debug("token successfully saved");
        } catch (Exception e) {
            throw new RuntimeException("Failed to save token from response", e);
        }
    }
616047
private JwtRequest getJwtRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JwtRequest jwtRequest = (JwtRequest) request.getAttribute(WebConstants.JWT_REQUEST_ATTR);
		if (jwtRequest == null) {
			String errorMsg = Tr.formatMessage(tc, "JWT_REQUEST_ATTRIBUTE_MISSING",
					new Object[] { request.getRequestURI(), WebConstants.JWT_REQUEST_ATTR });
			Tr.error(tc, errorMsg);
			response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
		}
		return jwtRequest;
	}
65264
Key getSharedSecretKey(JwtConsumerConfig config) throws KeyException {
		if (config == null) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "JWT consumer config object is null");
			}
			return null;
		}
		String sharedKey = config.getSharedKey();
		return createKeyFromSharedKey(sharedKey);
	}
720872
public static JsonWebSignature parse(JsonFactory jsonFactory, String tokenString)
      throws IOException {
    return parser(jsonFactory).parse(tokenString);
  }