org.wso2.balana.ctx.Attribute Java Examples

The following examples show how to use org.wso2.balana.ctx.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CarbonAttributeFinder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Converts DOM object to String. This is a helper method for creating cache key
 *
 * @param evaluationCtx EvaluationCtx
 * @return String Object
 * @throws TransformerException Exception throws if fails
 */
private String encodeContext(EvaluationCtx evaluationCtx) throws TransformerException {
    OutputStream stream = new ByteArrayOutputStream();
    evaluationCtx.getRequestCtx().encode(stream);
    String rowContext = stream.toString();
    String contextWithAttributeValues = rowContext + "][";

    StringBuilder builder = new StringBuilder();
    for (Attributes attributes : evaluationCtx.getRequestCtx().getAttributesSet()) {
        builder.append("<Attributes ").append(">");
        for (Attribute attribute : attributes.getAttributes()) {
            attribute.encode(builder);
        }
        builder.append("</Attributes>");
    }
    contextWithAttributeValues += builder.toString();

    return contextWithAttributeValues;
}
 
Example #2
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Private helper function to encode the attribute sets
 */
private void encodeAttributes(Set attributes, PrintStream out, Indenter indenter) {
    indenter.in();
    
    Iterator it = attributes.iterator();
    while (it.hasNext()) {
        Attribute attr = (Attribute) (it.next());
        out.print(indenter.makeString() + attr.encode());
    }
    
    indenter.out();
}
 
Example #3
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
private static Set<Attribute> parseAttributes(Node root) throws ParsingException {
    Set<Attribute> set = new HashSet<Attribute>();

    // the Environment section is just a list of Attributes
    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (DOMHelper.getLocalName(node).equals("Attribute"))
            set.add(Attribute.getInstance(node, XACMLConstants.XACML_VERSION_2_0));
    }

    return set;
}
 
Example #4
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #5
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param attributesSet
 * @param documentRoot the root node of the DOM tree for this request
 * @param resourceContent a text-encoded version of the content, suitable for including in the
 *            RequestType, including the root <code>RequestContent</code> node
 *
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, Set<Subject> subjects,
                  Set<Attribute> resource, Set<Attribute> action,  Set<Attribute> environment,
                  String resourceContent) throws IllegalArgumentException {

    this.attributesSet = attributesSet;
    this.documentRoot = documentRoot;
    this.subjects = subjects;
    this.resource = resource;
    this.action = action;
    this.environment = environment;
    this.resourceContent = resourceContent;
    this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0;
}
 
Example #6
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #7
Source File: Result.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the attributes that must be included in the response
 *
 * @param attributesSet  a <code>Set</code> of <code>Attributes</code>
 */
public void processAttributes(Set<Attributes> attributesSet){

    if(attributesSet == null){
        return;
    }

    Set<Attributes> newSet = new HashSet<Attributes>();

    for(Attributes attributes : attributesSet){
        Set<Attribute> attributeSet = attributes.getAttributes();
        if(attributeSet == null){
            continue;
        }
        Set<Attribute> newAttributeSet = new HashSet<Attribute>();
        for(Attribute attribute : attributeSet){
            if(attribute.isIncludeInResult()){
                newAttributeSet.add(attribute);
            }
        }

        if(newAttributeSet.size() > 0){
            Attributes newAttributes = new Attributes(attributes.getCategory(),
                                attributes.getContent(), newAttributeSet, attributes.getId());
            newSet.add(newAttributes);
        }
    }

    this.attributes = newSet;
}
 
Example #8
Source File: Obligation.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this <code>Obligation</code> into its XML form and writes this out to the provided
 * <code>StringBuilder<code>
 *
 * @param builder string stream into which the XML-encoded data is written
 */
public void encode(StringBuilder builder) {

    builder.append("<Obligation ObligationId=\"").append(obligationId.toString()).
            append("\" FulfillOn=\"").append(Result.DECISIONS[fulfillOn]).append("\">\n");
    for (Attribute assignment : assignments) {
        builder.append("<AttributeAssignment AttributeId=\"").
                append(assignment.getId().toString()).append("\" DataType=\"").
                append(assignment.getType().toString()).append("\">").
                append(assignment.getValue().encode()).append("</AttributeAssignment>\n");
    }
    builder.append("</Obligation>");
}
 
Example #9
Source File: Attributes.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this <code>Attributes</code> into its XML form and writes this out to the provided
 * <code>StringBuilder<code>
 *
 * @param builder string stream into which the XML-encoded data is written
 */
public void encode(StringBuilder builder) {

    builder.append("<Attributes Category=\"").append(category.toString()).append("\">");

    for(Attribute attribute : attributes){
        attribute.encode(builder);
    }
    if (content != null) {
    // TODO
    }

    builder.append("</Attributes>");
}
 
Example #10
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * This is to seperate JSON to attributes
 * @param jsonAttribute - the map of category string and the JSON Element
 * @param jsonCategory - the  main object category
 * @param categories - the set of categories
 * @throws RequestParseException
 * @throws UnknownIdentifierException
 */
private static void jsonAttributeSeperator(Map.Entry<String, JsonElement> jsonAttribute, JsonObject jsonCategory,
                                           Set<Attributes> categories) throws
        RequestParseException, UnknownIdentifierException {

    Node content = null;
    URI category = null;
    Set<Attribute> attributes = null;
    String id = null;

    if (EntitlementEndpointConstants.CATEGORY_DEFAULT.equals(jsonAttribute.getKey())) {
        if (jsonCategory.has(EntitlementEndpointConstants.CATEGORY_ID)) {
            category = stringCateogryToURI(jsonCategory
                    .get(EntitlementEndpointConstants.CATEGORY_ID)
                    .getAsString());
        }
    } else {
        if (category == null) {
            category = stringCateogryToURI(jsonAttribute.getKey());
        }
        if (jsonCategory.has(EntitlementEndpointConstants.ID)) {
            id = jsonCategory.get(EntitlementEndpointConstants.ID).getAsString();
        }
        if (jsonCategory.has(EntitlementEndpointConstants.CONTENT)) {
            DocumentBuilderFactory dbf;
            Document doc = null;

            String xmlContent = stringContentToXMLContent(jsonCategory
                    .get(EntitlementEndpointConstants.CONTENT)
                    .getAsString());
            dbf = IdentityUtil.getSecuredDocumentBuilderFactory();
            dbf.setNamespaceAware(true);

            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes())) {
                doc = dbf.newDocumentBuilder().parse(inputStream);
            } catch (Exception e) {
                throw new JsonParseException("DOM of request element can not be created from String.", e);
            }
            if (doc != null) {
                content = doc.getDocumentElement();
            }
        }

        // Add all category attributes
        if (jsonCategory.has(EntitlementEndpointConstants.ATTRIBUTE)) {
            if (jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE).isJsonArray()) {
                attributes = new HashSet<>();
                for (JsonElement jsonElement : jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE)
                        .getAsJsonArray()) {
                    attributes.add(jsonObjectToAttribute(jsonElement.getAsJsonObject()));
                }
            }
        }

    }
    //Build the Attributes object using above values
    Attributes attributesObj = new Attributes(category, content, attributes, id);
    categories.add(attributesObj);
}
 
Example #11
Source File: BalanaRequest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
public BalanaRequest(AbstractRequestCtx context, ValueFactory vf, JAXBContext jaxbContext) {
    subjectCategory = vf.createIRI(SUBJECT_CATEGORY);
    resourceCategory = vf.createIRI(RESOURCE_CATEGORY);
    actionCategory = vf.createIRI(ACTION_CATEGORY);
    requestTimeAttribute = vf.createIRI(CURRENT_DATETIME);
    this.jaxbContext = jaxbContext;

    of = new ObjectFactory();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    context.encode(out);
    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<RequestType> requestType = unmarshaller.unmarshal(new StreamSource(
                new ByteArrayInputStream(out.toByteArray())), RequestType.class);
        this.requestType = requestType.getValue();
    } catch (JAXBException e) {
        throw new MobiException(e);
    }

    subjectAttrs = new HashMap<>();
    resourceAttrs = new HashMap<>();
    actionAttrs = new HashMap<>();
    context.getAttributesSet().forEach(attributes -> {
        Set<Attribute> attributeSet = attributes.getAttributes();
        switch (attributes.getCategory().toString()) {
            case SUBJECT_CATEGORY:
                attributeSet.forEach(attribute -> {
                    if (attribute.getId().toString().equals(XACML.SUBJECT_ID)) {
                        this.subjectId = vf.createIRI(attribute.getValue().encode());
                    } else {
                        this.subjectAttrs.put(attribute.getId().toString(), getLiteral(attribute.getValue(), vf));
                    }
                });
                if (this.subjectId == null) {
                    throw new IllegalArgumentException("No Subject ID passed in Request");
                }
                break;
            case XACML.RESOURCE_CATEGORY:
                attributeSet.forEach(attribute -> {
                    if (attribute.getId().toString().equals(XACML.RESOURCE_ID)) {
                        this.resourceId = vf.createIRI(attribute.getValue().encode());
                    } else {
                        this.resourceAttrs.put(attribute.getId().toString(), getLiteral(attribute.getValue(), vf));
                    }
                });
                if (this.resourceId == null) {
                    throw new IllegalArgumentException("No Resource ID passed in the request");
                }
                break;
            case XACML.ACTION_CATEGORY:
                attributeSet.forEach(attribute -> {
                    if (attribute.getId().toString().equals(XACML.ACTION_ID)) {
                        this.actionId = vf.createIRI(attribute.getValue().encode());
                    } else {
                        this.actionAttrs.put(attribute.getId().toString(), getLiteral(attribute.getValue(), vf));
                    }
                });
                if (this.actionId == null) {
                    throw new IllegalArgumentException("No Action ID passed in the request");
                }
                break;
            case XACML.ENVIRONMENT_CATEGORY:
                attributeSet.forEach(attribute -> {
                    if (attribute.getId().toString().equals(XACML.CURRENT_DATETIME)) {
                        this.requestTime = OffsetDateTime.parse(attribute.getValue().encode());
                    }
                });
                if (this.requestTime == null) {
                    throw new IllegalArgumentException("No Environment Current Date Time passed in the request");
                }
                break;
            default:
                throw new IllegalArgumentException("Unsupported category in request");
        }
    });
}
 
Example #12
Source File: TestJSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testParse() {
    AttributeValue attributeValue = new StringAttribute("http://127.0.0.1");
    List<AttributeValue> attributeValues = new ArrayList<>();
    attributeValues.add(attributeValue);

    Attribute attribute = new Attribute(URI.create("urn:oasis:names:tc:xacml:1.0:resource:resource-id"),
            null, null, null, attributeValues, false, XACMLConstants.XACML_VERSION_3_0);
    Set<Attribute> attributeSet = new HashSet<>();
    attributeSet.add(attribute);

    Attributes category = new Attributes(URI.create(EntitlementEndpointConstants.CATEGORY_RESOURCE_URI),
            attributeSet);
    Set<Attributes> categories = new HashSet<>();
    categories.add(category);

    RequestCtx requestCtx = new RequestCtx(categories, null);


    String jsonRequest = "{\n" +
            "  \"Request\":{\n" +
            "    \"Action\":{\n" +
            "      \"Attribute\":[{\n" +
            "        \"AttributeId\":\"urn:oasis:names:tc:xacml:1.0:action:action-id\",\n" +
            "        \"Value\":\"read\"\n" +
            "      }]\n" +
            "    },\n" +
            "    \"Resource\":{\n" +
            "      \"Attribute\":[{\n" +
            "        \"AttributeId\":\"urn:oasis:names:tc:xacml:1.0:resource:resource-id\",\n" +
            "        \"Value\":\"http://127.0.0.1/service/very_secure/\"\n" +
            "      }]\n" +
            "    }\n" +
            "  }\n" +
            "}";

    String jsonRequest2 = "{\"Request\":\n" +
            "{\n" +
            "\"AccessSubject\":{\n" +
            "            \"Content\": \"PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8Y2F0YWxvZz48Ym9vayBpZD0iYmsxMDEiPjxhdXRob3I+R2FtYmFyZGVsbGEsIE1hdHRoZXc8L2F1dGhvcj48dGl0bGU+WE1MIERldmVsb3BlcidzIEd1aWRlPC90aXRsZT48Z2VucmU+Q29tcHV0ZXI8L2dlbnJlPjxwcmljZT40NC45NTwvcHJpY2U+PHB1Ymxpc2hfZGF0ZT4yMDAwLTEwLTAxPC9wdWJsaXNoX2RhdGU+PGRlc2NyaXB0aW9uPkFuIGluLWRlcHRoIGxvb2sgYXQgY3JlYXRpbmcgYXBwbGljYXRpb25zIHdpdGggWE1MLjwvZGVzY3JpcHRpb24+PC9ib29rPjwvY2F0YWxvZz4=\"\n" +
            "}\n" +
            "}}";

    try {
        RequestCtx requestCtx1 = JSONRequestParser.parse(jsonRequest);
    } catch (Exception e) {
        log.error("Exception in JSON Parser Test");
    }


}
 
Example #13
Source File: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Create json object value of an Attribute
 *
 * @param attributes an element of type Attributes
 * @return a JSONObject
 */
private static JsonObject getJsonObject(Attributes attributes) {

    JsonObject jsonObject = new JsonObject();
    JsonArray jsonArray = new JsonArray();
    for (Object att : attributes.getAttributes().toArray()) {
        Attribute attrib = (Attribute) att;
        if (attrib.isIncludeInResult()) {
            JsonObject element = new JsonObject();
            if (attrib.getId() != null) {
                if (xacmlJSONProfileShortFormEnable) {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_ID, uriToShortenForm(attrib
                            .getId().toString()));
                } else {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_ID, attrib.getId().toString());
                }
            }
            if (attrib.getValues() != null) {
                for (AttributeValue val : attrib.getValues()) {
                    if (((StringAttribute) val).getValue() != null) {
                        element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_VALUE,
                                ((StringAttribute) val).getValue());
                    }
                }
            }
            element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_INCLUDE_IN_RESULT,
                    String.valueOf(attrib.isIncludeInResult()));
            if (attrib.getType() != null) {
                if (xacmlJSONProfileShortFormEnable) {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE,
                            uriToShortenForm(attrib.getType().toString()));
                } else {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE,
                            attrib.getType().toString());
                }
            }
            jsonArray.add(element);
        }
    }
    jsonObject.add(EntitlementEndpointConstants.ATTRIBUTE, jsonArray);
    return jsonObject;
}
 
Example #14
Source File: Attributes.java    From balana with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor that creates a new <code>Attributes</code> based on
 * the given elements.
 * @param category category of the Attributes element whether it is subject, action and etc
 * @param content content of the Attributes element that can be a XML data
 * @param attributes  a <code>Set</code> of <code>Attribute</code>
 * that contains in <code>Attributes</code> 
 * @param id   id of the Attribute element
 */
public Attributes(URI category, Node content, Set<Attribute> attributes, String id) {
    this.category = category;
    this.content = content;
    this.attributes = attributes;
    this.id = id;
}
 
Example #15
Source File: Attributes.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Returns list of attribute that contains in the attributes element
 *
 * @return  list of <code>Attribute</code>
 */
public Set<Attribute> getAttributes() {
    return attributes;
}
 
Example #16
Source File: Obligation.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that takes all the data associated with an obligation. The attribute assignment
 * list contains <code>Attribute</code> objects, but only the fields used by the
 * AttributeAssignmentType are used.
 *
 * @param obligationId the obligation's id
 * @param fulfillOn the effect denoting when to fulfill this obligation
 * @param assignments a <code>List</code> of <code>Attribute</code>s
 */
public Obligation(URI obligationId, int fulfillOn, List<Attribute> assignments) {
    this.obligationId = obligationId;
    this.fulfillOn = fulfillOn;
    this.assignments = Collections.unmodifiableList(new ArrayList<Attribute>(assignments));
}
 
Example #17
Source File: Obligation.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the attribute assignment data in this obligation. The <code>List</code> contains
 * objects of type <code>Attribute</code> with only the correct attribute fields being used.
 *
 * @return the assignments
 */
public List<Attribute> getAssignments() {
    return assignments;
}
 
Example #18
Source File: Attributes.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that creates a new <code>Attributes</code> based on
 * the given elements.
 * @param category category of the Attributes element whether it is subject, action and etc
 * @param attributes  a <code>Set</code> of <code>Attribute</code>
 * that contains in <code>Attributes</code>
 */
public Attributes(URI category,Set<Attribute> attributes) {
    this(category, null, attributes, null);
}
 
Example #19
Source File: RequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param subjects
 * @param resource
 * @param action
 * @param environment
 * @throws IllegalArgumentException
 */
public RequestCtx(Set<Subject> subjects, Set<Attribute> resource, Set<Attribute> action,
                  Set<Attribute> environment) throws IllegalArgumentException {
    this(null, null, subjects, resource, action, environment, null);

}