Obtains the JWK string that is active in the specified config and prints
it in JSON format in the response. If a JWK is not found, the response
will be empty.

@param response
@param jwtConfig
@throws IOException
493658
private void processJWKRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {

		/*
		 * if (!jwtConfig.isJwkEnabled()) { String errorMsg =
		 * Tr.formatMessage(tc, "JWK_ENDPOINT_JWK_NOT_ENABLED", new Object[] {
		 * jwtConfig.getId() }); Tr.error(tc, errorMsg);
		 * response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
		 * return; }
		 */

		String signatureAlg = jwtConfig.getSignatureAlgorithm();
		if (!Constants.SIGNATURE_ALG_RS256.equals(signatureAlg)) {
			String errorMsg = Tr.formatMessage(tc, "JWK_ENDPOINT_WRONG_ALGORITHM",
					new Object[] { jwtConfig.getId(), signatureAlg, Constants.SIGNATURE_ALG_RS256 });
			Tr.error(tc, errorMsg);
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
			return;
		}

		String jwkString = jwtConfig.getJwkJsonString();

		addNoCacheHeaders(response);
		response.setStatus(200);

		if (jwkString == null) {
			return;
		}
		try {
			PrintWriter pw = response.getWriter();
			response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
			pw.write(jwkString);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
			}
		}
	}
895680
private synchronized Jwt getJwt(ICacheStrategy cacheStrategy, Jwt.Key key) {
        Jwt result = cacheStrategy.getCachedJwt(key);
        if(result == null) {
            //cache an empty JWT first.
            result = new Jwt(key);
            cacheStrategy.cacheJwt(key, result);
        }
        return result;
    }
1339151
public static String buildSecretFromJwk(final String json) {
        CommonHelper.assertNotBlank("json", json);

        try {
            final OctetSequenceKey octetSequenceKey = OctetSequenceKey.parse(json);
            return new String(octetSequenceKey.toByteArray(), "UTF-8");
        } catch (final UnsupportedEncodingException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
1111254
public HttpClientResponseBuilder doReturnJSON(String response, Charset charset) {
        return responseBuilder.doReturnJSON(response, charset);
    }
923380
private JsonParser parseResponse(Response response) throws IOException {
		InputStream is = response.getInputStream();
		Reader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		return new JsonParser(new JsonLexer(r));
	}
556732
function JWR(responseCtx) {
            this.body = responseCtx.body || {};
            this.headers = responseCtx.headers || {};
            this.statusCode = responseCtx.statusCode || 200;
        }
256482
@POST
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(
            value = "Assert login credentials",
            notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.",
            response = String.class
    )
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 401, message = "Unauthorized")
    })
    @AuthenticationNotRequired
    public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) {
        final Authenticator auth = new Authenticator(username, password);
        try {
            final Principal principal = auth.authenticate();
            if (principal != null) {
                LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username
                        + " / ip address: " + super.getRemoteAddress()
                        + " / agent: " + super.getUserAgent() + ")");

                final JsonWebToken jwt = new JsonWebToken();
                final String token = jwt.createToken(principal);
                return Response.ok(token).build();
            }
        } catch (AuthenticationException e) {
            LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: "
                    + username + " / ip address: " + super.getRemoteAddress()
                    + " / agent: " + super.getUserAgent() + ")");
        }
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
1335495
public static void makeJsonResponse(HttpResponse response, String encoded) {
        StringEntity ent = new StringEntity(encoded, ContentType.APPLICATION_JSON);
        response.setEntity(ent);
    }
165323
def jwks(self, context):
        
        return Response(json.dumps(self.provider.jwks), content="application/json")
241505
protected static String responseToJson(Response response) throws JsonProcessingException {
        ObjectMapper mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.writeValueAsString(response);
    }
952907
@Override
	// @FFDCIgnore(Exception.class)
	public Subject handleJwtSSOTokenValidation(Subject subject, String encodedjwt) throws WSLoginFailedException {
		// TODO Auto-generated method stub		
        String msg = Tr.formatMessage(tc, "JWTSSO_CONFIG_INVALID_OR_TOKEN_INVALID", new Object[] {});		
		Subject resultSub = null;

		JwtSsoTokenUtils tokenUtil = getJwtSsoTokenConsumerUtils();
		if (tokenUtil != null && encodedjwt != null) {
			if (subject != null) {
				try {
					resultSub = tokenUtil.handleJwtSsoTokenValidationWithSubject(subject, encodedjwt);
				} catch (Exception e) {
					throw new WSLoginFailedException(e.getLocalizedMessage());
				}
			} else {
				try {
					resultSub = tokenUtil.handleJwtSsoTokenValidation(encodedjwt);
				} catch (Exception e) {
					throw new WSLoginFailedException(e.getLocalizedMessage());
				}
			}
		} else {
			throw new WSLoginFailedException(msg);
		}

		if (resultSub == null) {
			throw new WSLoginFailedException(msg);
		}

		return resultSub;
	}
323583
public String extractJwtFromTokenEndpointResponse(Page response) throws Exception {
        JsonReader reader = Json.createReader(new StringReader(WebResponseUtils.getResponseText(response)));
        JsonObject jsonResponse = reader.readObject();
        return jsonResponse.getString("token");
    }
906763
public void print(String s) throws IOException
	{
		//PK89810, If WCCustomProperties.FINISH_RESPONSE_ON_CLOSE is set and stream is already obtained and closed. 
		// We will not allow user to print more data if the above case is met, outputstreamClosed will be true and default is false.
		if (!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || !outputstreamClosed ) //PK89810
		{
		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
			logger.logp(Level.FINE, CLASS_NAME,"print", "print --> "+s);
                }
                if(s != null) {  // PQ88872
                    if (!_hasWritten && obs != null)
                    {
                            _hasWritten = true;
            			if (obsList!=null){
            				for (int i=0;i<obsList.size();i++){
            					obsList.get(i).alertFirstWrite();
            				}
            			}
            			else {
                            obs.alertFirstWrite();
                    }
            		}
			int len = s.length();
			if (limit > -1)
			{
				if (total + len > limit)
				{
					len = limit - total;
					except = new WriteBeyondContentLengthException();
				}
			}
			if(this.getBufferSize() != 0){		 // PM44112 
					int off = 0;
					while (len > 0)
					{
						int n = buf.length - count;
						if (n == 0)
						{
							response.setFlushMode(false);
							flushBytes();
							response.setFlushMode(true);
							n = buf.length - count;
						}
						if (n > len)
						{
							n = len;
						}
						//
						// NOTE:  this getBytes call is deprecated ... it doesn't work
						// correctly for multibyte characters, and doesn't take account
						// of the character encoding that the client expects.
						//
						s.getBytes(off, off + n, buf, count);
						
						count += n;
						total += n;
						off += n;
						len -= n;
					}
				} // PM44112 Start
				else if(getBufferSize() == 0) {	
					
					byte[] origBuf=buf; // store the original buff , which is 0
					buf = s.getBytes();	// update buf with the String to print.
					count = buf.length;
					total+=count; // keep the count and the total written
					
					if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
						logger.logp(Level.FINE, CLASS_NAME,"print",  "response Buffersize is set to zero , to print --> "+ count +" total -->"+  total);
					
					
					response.setFlushMode(true);
					flushBytes();				
					buf=origBuf; // set it back to original buff, i.e. 0 value
					
					if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
						logger.logp(Level.FINE, CLASS_NAME,"print",  "after flushbytes, buf --> "+ buf.length +" count --> "+  count+" total -->"+  total);
					
				}// PM44112 End
			check();
		} // PQ88872
	}
		else{//PK89810 start
			if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
				logger.logp(Level.FINE, CLASS_NAME,"print", "print not allowed, outputstreamClosed value --> " + outputstreamClosed);			
		}//PK89810 End
	}
46581
@RequestMapping(value = "/gettoken", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage getToken(HttpServletRequest request, HttpServletResponse response) {
        String username = StringUtil.EMPTY_STRING;
        String password = StringUtil.EMPTY_STRING;
        ResponseMessage result = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            if (json.has("username")) {
                username = json.getString("username");
            }
            if (json.has("password")) {
                password = json.getString("password");
            }

            mUserService.validLoginUser(username, password);
            String token = mUserService.createToken(username, request.getRemoteAddr());
            result.setStatus(true);
            result.setData(token);
        } catch (Exception e) {
            result.setStatus(false);
            result.setData(e.getMessage());
        }
        return result;
    }
26977
public static String formatResponse(Response response) {
        if (response == null) {
            return "";
        }
        StringBuilder output = new StringBuilder();
        if (response.isData()) {
            output.append(DIV_I);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            if (response.getArrayData() != null) {
                output.append(gson.toJson(response.getArrayData()));
            }
            if (response.getObjectData() != null) {
                output.append(gson.toJson(response.getObjectData()));
            }
            output.append(END_IDIV);
        }
        return formatHTML(output.toString());
    }
1202647
@RequestMapping(value = "/invoke", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage invoke(HttpServletRequest request, HttpServletResponse response) {
        ResponseMessage res = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            ValidMessage rm = (ValidMessage) tgtools.util.JsonParseHelper.parseToObject(json, ValidMessage.class);

            mUserService.tokenLogin(request.getRemoteAddr(), rm.getUser(), rm.getToken());

            Object obj = restCommand.process(rm.getOperation(), rm.getData());
            res.setStatus(true);
            res.setData(obj);
        } catch (Exception e) {
            res.setStatus(false);
            res.setData(e.getMessage());
        }
        try {
            System.out.println("client结果：" + tgtools.util.JsonParseHelper.parseToJsonObject(res).toString());
        } catch (Exception d) {
        }
        return res;
    }
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;
    }