Search in sources :

Example 46 with JSONObject

use of net.sf.json.JSONObject in project summer-bean by cn-cerc.

the class SAPISecurity method checkVerify.

/**
 * 检测验证码
 *
 * @param user
 *            用户账号
 * @param verifyCode
 *            验证码
 * @return true:成功,若失败可用getMessage取得错误信息
 */
public boolean checkVerify(String user, String verifyCode) {
    Map<String, String> params = new HashMap<>();
    params.put("ip", getRemoteIP());
    params.put("user", user);
    params.put("verifyCode", verifyCode);
    try {
        String result = doPost(String.format("%s/forms/security.checkVerify", getHost()), params);
        JSONObject json = JSONObject.fromObject(result);
        if (json.has("result")) {
            this.setMessage(json.getString("message"));
            return json.getBoolean("result");
        } else {
            this.setMessage(result);
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        this.setMessage(e.getMessage());
        return false;
    }
}
Also used : JSONObject(net.sf.json.JSONObject) HashMap(java.util.HashMap)

Example 47 with JSONObject

use of net.sf.json.JSONObject in project blueocean-plugin by jenkinsci.

the class GithubServerContainer method create.

@CheckForNull
public ScmServerEndpoint create(@JsonBody JSONObject request) {
    List<ErrorMessage.Error> errors = Lists.newLinkedList();
    // Validate name
    final String name = (String) request.get(GithubServer.NAME);
    if (StringUtils.isEmpty(name)) {
        errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required"));
    } else {
        GithubServer byName = findByName(name);
        if (byName != null) {
            errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'"));
        }
    }
    // Validate url
    final String url = (String) request.get(GithubServer.API_URL);
    if (StringUtils.isEmpty(url)) {
        errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required"));
    } else {
        Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url);
        if (byUrl != null) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'"));
        }
    }
    if (StringUtils.isNotEmpty(url)) {
        // Validate that the URL represents a Github API endpoint
        try {
            HttpURLConnection connection = HttpRequest.get(url).connect();
            if (connection.getHeaderField("X-GitHub-Request-Id") == null) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER));
            } else {
                boolean isGithubCloud = false;
                boolean isGithubEnterprise = false;
                try {
                    InputStream inputStream;
                    int code = connection.getResponseCode();
                    if (200 <= code && code < 300) {
                        inputStream = HttpRequest.getInputStream(connection);
                    } else {
                        inputStream = HttpRequest.getErrorStream(connection);
                    }
                    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
                    };
                    Map<String, String> responseBody = GithubScm.om.readValue(inputStream, typeRef);
                    isGithubCloud = code == 200 && responseBody.containsKey("current_user_url");
                    isGithubEnterprise = code == 401 && responseBody.containsKey("message");
                } catch (IOException ioe) {
                    LOGGER.log(Level.INFO, "Could not parse response body from Github");
                }
                if (!isGithubCloud && !isGithubEnterprise) {
                    errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL));
                }
            }
        } catch (Throwable e) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString()));
            LOGGER.log(Level.INFO, "Could not connect to Github", e);
        }
    }
    if (errors.isEmpty()) {
        SecurityContext old = null;
        try {
            // We need to escalate privilege to add user defined endpoint to
            old = ACL.impersonate(ACL.SYSTEM);
            GitHubConfiguration config = GitHubConfiguration.get();
            String sanitizedUrl = discardQueryString(url);
            Endpoint endpoint = new Endpoint(sanitizedUrl, name);
            if (!config.addEndpoint(endpoint)) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'"));
            } else {
                return new GithubServer(endpoint, getLink());
            }
        } finally {
            // reset back to original privilege level
            if (old != null) {
                SecurityContextHolder.setContext(old);
            }
        }
    }
    ErrorMessage message = new ErrorMessage(400, "Failed to create Github server");
    message.addAll(errors);
    throw new ServiceException.BadRequestException(message);
}
Also used : GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) HashMap(java.util.HashMap) InputStream(java.io.InputStream) IOException(java.io.IOException) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) HttpURLConnection(java.net.HttpURLConnection) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) SecurityContext(org.acegisecurity.context.SecurityContext) JSONObject(net.sf.json.JSONObject) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) CheckForNull(javax.annotation.CheckForNull)

Example 48 with JSONObject

use of net.sf.json.JSONObject in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationServiceImpl method getToken.

@Override
public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer expiryTimeInMins, @Nullable @QueryParameter("maxExpiryTimeInMins") Integer maxExpiryTimeInMins) {
    long expiryTime = Long.getLong("EXPIRY_TIME_IN_MINS", DEFAULT_EXPIRY_IN_SEC);
    int maxExpiryTime = Integer.getInteger("MAX_EXPIRY_TIME_IN_MINS", DEFAULT_MAX_EXPIRY_TIME_IN_MIN);
    if (maxExpiryTimeInMins != null) {
        maxExpiryTime = maxExpiryTimeInMins;
    }
    if (expiryTimeInMins != null) {
        if (expiryTimeInMins > maxExpiryTime) {
            throw new ServiceException.BadRequestException(String.format("expiryTimeInMins %s can't be greater than %s", expiryTimeInMins, maxExpiryTime));
        }
        expiryTime = expiryTimeInMins * 60;
    }
    Authentication authentication = Jenkins.getAuthentication();
    String userId = authentication.getName();
    User user = User.get(userId, false, Collections.emptyMap());
    String email = null;
    String fullName = null;
    if (user != null) {
        fullName = user.getFullName();
        userId = user.getId();
        Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class);
        if (p != null)
            email = p.getAddress();
    }
    Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-jwt");
    String issuer = "blueocean-jwt:" + ((plugin != null) ? plugin.getWrapper().getVersion() : "");
    JwtToken jwtToken = new JwtToken();
    jwtToken.claim.put("jti", UUID.randomUUID().toString().replace("-", ""));
    jwtToken.claim.put("iss", issuer);
    jwtToken.claim.put("sub", userId);
    jwtToken.claim.put("name", fullName);
    long currentTime = System.currentTimeMillis() / 1000;
    jwtToken.claim.put("iat", currentTime);
    jwtToken.claim.put("exp", currentTime + expiryTime);
    jwtToken.claim.put("nbf", currentTime - DEFAULT_NOT_BEFORE_IN_SEC);
    // set claim
    JSONObject context = new JSONObject();
    JSONObject userObject = new JSONObject();
    userObject.put("id", userId);
    userObject.put("fullName", fullName);
    userObject.put("email", email);
    JwtAuthenticationStore authenticationStore = getJwtStore(authentication);
    authenticationStore.store(authentication, context);
    context.put("user", userObject);
    jwtToken.claim.put("context", context);
    return jwtToken;
}
Also used : JwtToken(io.jenkins.blueocean.auth.jwt.JwtToken) User(hudson.model.User) JSONObject(net.sf.json.JSONObject) Authentication(org.acegisecurity.Authentication) Mailer(hudson.tasks.Mailer) Plugin(hudson.Plugin) JwtAuthenticationStore(io.jenkins.blueocean.auth.jwt.JwtAuthenticationStore)

Example 49 with JSONObject

use of net.sf.json.JSONObject in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationServiceImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    Page page = webClient.goTo("jwt-auth/token/", null);
    String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    System.out.println(token);
    System.out.println(jsw.toString());
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
    // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
    // System.out.println(valuePair);
    // }
    JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
    System.out.println(jsonObject.toString());
    RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("alice", claims.getSubject());
    Map<String, Object> claimMap = claims.getClaimsMap();
    Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
    Map<String, String> userContext = (Map<String, String>) context.get("user");
    Assert.assertEquals("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Example 50 with JSONObject

use of net.sf.json.JSONObject in project blueocean-plugin by jenkinsci.

the class PipelineStepImpl method parseValue.

private Object parseValue(InputStepExecution execution, JSONArray parameters, StaplerRequest request) throws IOException, InterruptedException {
    Map<String, Object> mapResult = new HashMap<String, Object>();
    InputStep input = execution.getInput();
    for (Object o : parameters) {
        JSONObject p = (JSONObject) o;
        String name = (String) p.get(NAME_ELEMENT);
        if (name == null) {
            throw new ServiceException.BadRequestException("name is required parameter element");
        }
        ParameterDefinition d = null;
        for (ParameterDefinition def : input.getParameters()) {
            if (def.getName().equals(name))
                d = def;
        }
        if (d == null)
            throw new ServiceException.BadRequestException("No such parameter definition: " + name);
        ParameterValue v = d.createValue(request, p);
        if (v == null) {
            continue;
        }
        mapResult.put(name, convert(name, v));
    }
    // If a destination value is specified, push the submitter to it.
    String valueName = input.getSubmitterParameter();
    if (valueName != null && !valueName.isEmpty()) {
        Authentication a = Jenkins.getAuthentication();
        mapResult.put(valueName, a.getName());
    }
    switch(mapResult.size()) {
        case 0:
            // no value if there's no parameter
            return null;
        case 1:
            return mapResult.values().iterator().next();
        default:
            return mapResult;
    }
}
Also used : JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) FileParameterValue(hudson.model.FileParameterValue) ParameterValue(hudson.model.ParameterValue) HashMap(java.util.HashMap) Authentication(org.acegisecurity.Authentication) BlueInputStep(io.jenkins.blueocean.rest.model.BlueInputStep) InputStep(org.jenkinsci.plugins.workflow.support.steps.input.InputStep) JSONObject(net.sf.json.JSONObject) ParameterDefinition(hudson.model.ParameterDefinition)

Aggregations

JSONObject (net.sf.json.JSONObject)493 Test (org.junit.Test)99 JSONArray (net.sf.json.JSONArray)94 IOException (java.io.IOException)49 HashMap (java.util.HashMap)48 ArrayList (java.util.ArrayList)36 JSON (net.sf.json.JSON)26 PrintWriter (java.io.PrintWriter)25 Map (java.util.Map)23 File (java.io.File)21 InputStream (java.io.InputStream)18 URISyntaxException (java.net.URISyntaxException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 JsonConfig (net.sf.json.JsonConfig)14 FreeStyleBuild (hudson.model.FreeStyleBuild)13 URI (java.net.URI)13 URL (java.net.URL)13 JSONException (net.sf.json.JSONException)13 Context (org.zaproxy.zap.model.Context)12 Transactional (org.springframework.transaction.annotation.Transactional)11