Java Code Examples for com.sun.security.auth.UserPrincipal#getName()

The following examples show how to use com.sun.security.auth.UserPrincipal#getName() . 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: MqttSubscribeResource.java    From mithqtt with Apache License 2.0 4 votes vote down vote up
/**
 * Handle MQTT Subscribe Request in RESTful style
 * Granted QoS Levels will send back to client.
 * Retain Messages matched the subscriptions will NOT send back to client.
 */
@PermitAll
@POST
public ResultEntity<List<MqttGrantedQoS>> subscribe(@PathParam("clientId") String clientId, @Auth UserPrincipal user, @QueryParam("protocol") @DefaultValue("4") byte protocol,
                                                    @QueryParam("packetId") @DefaultValue("0") int packetId,
                                                    List<Subscription> subscriptions) {
    String userName = user.getName();
    MqttVersion version = MqttVersion.fromProtocolLevel(protocol);
    List<MqttTopicSubscription> requestSubscriptions = new ArrayList<>();
    List<MqttTopicSubscriptionGranted> grantedSubscriptions = new ArrayList<>();

    // HTTP interface require valid Client Id
    if (!this.validator.isClientIdValid(clientId)) {
        logger.debug("Protocol violation: Client id {} not valid based on configuration", clientId);
        throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
    }

    // Validate Topic Filter based on configuration
    for (Subscription subscription : subscriptions) {
        if (!this.validator.isTopicFilterValid(subscription.getTopic())) {
            logger.debug("Protocol violation: Client {} subscription {} is not valid based on configuration", clientId, subscription.getTopic());
            throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
        }
        MqttQoS requestQos;
        try {
            requestQos = MqttQoS.valueOf(subscription.getQos());
        } catch (IllegalArgumentException e) {
            logger.debug("Protocol violation: Client {} subscription qos {} is not valid", clientId, subscription.getQos());
            throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
        }
        requestSubscriptions.add(new MqttTopicSubscription(subscription.getTopic(), requestQos));
    }

    logger.debug("Message received: Received SUBSCRIBE message from client {} user {}", clientId, userName);

    // Authorize client subscribe using provided Authenticator
    List<MqttGrantedQoS> grantedQosLevels = this.authenticator.authSubscribe(clientId, userName, requestSubscriptions);
    if (subscriptions.size() != grantedQosLevels.size()) {
        logger.warn("Authorization error: SUBSCRIBE message's subscriptions count not equal to granted QoS count");
        throw new AuthorizeException(new ErrorEntity(ErrorCode.UNAUTHORIZED));
    }
    logger.trace("Authorization granted on topic {} as {} for client {}", ArrayUtils.toString(requestSubscriptions), ArrayUtils.toString(grantedQosLevels), clientId);

    for (int i = 0; i < requestSubscriptions.size(); i++) {

        MqttGrantedQoS grantedQoS = grantedQosLevels.get(i);
        String topic = requestSubscriptions.get(i).topic();
        List<String> topicLevels = Topics.sanitize(topic);
        grantedSubscriptions.add(new MqttTopicSubscriptionGranted(topic, grantedQoS));

        // Granted only
        if (grantedQoS != MqttGrantedQoS.NOT_GRANTED) {

            // If a Server receives a SUBSCRIBE Packet containing a Topic Filter that is identical to an existing
            // Subscription’s Topic Filter then it MUST completely replace that existing Subscription with a new
            // Subscription. The Topic Filter in the new Subscription will be identical to that in the previous Subscription,
            // although its maximum QoS value could be different.
            logger.trace("Update subscription: Update client {} subscription with topic {} QoS {}", clientId, topic, grantedQoS);
            this.storage.updateSubscription(clientId, topicLevels, MqttQoS.valueOf(grantedQoS.value()));
        }
    }

    // Pass message to 3rd party application
    Message<MqttPacketIdVariableHeader, MqttSubscribePayloadGranted> msg = new Message<>(
            new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0),
            new MqttAdditionalHeader(version, clientId, userName, null),
            MqttPacketIdVariableHeader.from(packetId),
            new MqttSubscribePayloadGranted(grantedSubscriptions));
    this.cluster.sendToApplication(msg);

    return new ResultEntity<>(grantedQosLevels);
}
 
Example 2
Source File: MqttUnsubscribeResource.java    From mithqtt with Apache License 2.0 4 votes vote down vote up
/**
 * Handle MQTT Un-Subscribe Request in RESTful style
 */
@PermitAll
@POST
public ResultEntity<Boolean> unsubscribe(@PathParam("clientId") String clientId, @Auth UserPrincipal user, @QueryParam("protocol") @DefaultValue("4") byte protocol,
                                         @QueryParam("packetId") @DefaultValue("0") int packetId,
                                         List<String> topics) {
    String userName = user.getName();
    MqttVersion version = MqttVersion.fromProtocolLevel(protocol);

    // HTTP interface require valid Client Id
    if (!this.validator.isClientIdValid(clientId)) {
        logger.debug("Protocol violation: Client id {} not valid based on configuration", clientId);
        throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
    }

    // Validate Topic Filter based on configuration
    for (String topic : topics) {
        if (!this.validator.isTopicFilterValid(topic)) {
            logger.debug("Protocol violation: Client {} un-subscription {} is not valid based on configuration", clientId, topic);
            throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
        }
    }

    logger.debug("Message received: Received UNSUBSCRIBE message from client {} user {} topics {}", clientId, userName, ArrayUtils.toString(topics));

    // The Topic Filters (whether they contain wildcards or not) supplied in an UNSUBSCRIBE packet MUST be
    // compared character-by-character with the current set of Topic Filters held by the Server for the Client. If
    // any filter matches exactly then its owning Subscription is deleted, otherwise no additional processing
    // occurs
    // If a Server deletes a Subscription:
    // It MUST stop adding any new messages for delivery to the Client.
    //1 It MUST complete the delivery of any QoS 1 or QoS 2 messages which it has started to send to
    // the Client.
    // It MAY continue to deliver any existing messages buffered for delivery to the Client.
    topics.forEach(topic -> {
        logger.trace("Remove subscription: Remove client {} subscription with topic {}", clientId, topic);
        this.storage.removeSubscription(clientId, Topics.sanitize(topic));
    });

    // Pass message to 3rd party application
    Message<MqttPacketIdVariableHeader, MqttUnsubscribePayload> msg = new Message<>(
            new MqttFixedHeader(MqttMessageType.UNSUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0),
            new MqttAdditionalHeader(version, clientId, userName, null),
            MqttPacketIdVariableHeader.from(packetId),
            new MqttUnsubscribePayload(topics));
    this.cluster.sendToApplication(msg);

    return new ResultEntity<>(true);
}