com.sun.security.auth.UserPrincipal Java Examples

The following examples show how to use com.sun.security.auth.UserPrincipal. 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 6 votes vote down vote up
/**
 * Get client's exist subscriptions
 */
@PermitAll
@GET
public ResultEntity<List<Subscription>> subscribe(@PathParam("clientId") String clientId, @Auth UserPrincipal user) {
    List<Subscription> subscriptions = 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));
    }

    // Read client's subscriptions from storage
    Map<String, MqttQoS> map = this.storage.getClientSubscriptions(clientId);
    map.forEach((topic, qos) -> subscriptions.add(new Subscription(topic, qos.value())));

    return new ResultEntity<>(subscriptions);
}
 
Example #2
Source File: DefaultSecurityManagerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test addUser method.
 */
@Test
public void testAddUser() {
    TestWebApplicationRequest request = new TestWebApplicationRequest();
    request.setUserPrincipal(new UserPrincipal("username"));
    DefaultSecurityManager securityManager = new DefaultSecurityManager();
    securityManager.addUser("username", "password", new String[]{"role1", "role2"});
    assertTrue(securityManager.isUserInRole(request, "role1"));
}
 
Example #3
Source File: InMemoryLoginModule.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    if (!loginSucceeded) {
        return false;
    }
    userPrincipal = new UserPrincipal(username);
    subject.getPrincipals().add(userPrincipal);
    return true;
}
 
Example #4
Source File: AccountControllerTest.java    From microservice-skeleton with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentAccount() throws Exception {
    final Account account = new Account();
    account.setUsername("test");

    when(accountService.findByUserName(account.getUsername())).thenReturn(account);

    mockMvc.perform(get("/current").principal(new UserPrincipal(account.getUsername())))
            .andExpect(jsonPath("$.username").value(account.getUsername()))
            .andExpect(status().isOk());
}
 
Example #5
Source File: UserStoreLoginModule.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    if (success) {
        userPrincipal = new UserPrincipal(authenticationId);
        if (!subject.getPrincipals().contains(userPrincipal)) {
            subject.getPrincipals().add(userPrincipal);
        }
    }
    cleanAuthInputData();
    return success;
}
 
Example #6
Source File: DefaultSecurityManagerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test removeUser method.
 */
@Test
public void testRemoveUser() {
    TestWebApplicationRequest request = new TestWebApplicationRequest();
    request.setUserPrincipal(new UserPrincipal("username"));
    DefaultSecurityManager securityManager = new DefaultSecurityManager();
    securityManager.addUser("username", "password", new String[]{"role1", "role2"});
    assertTrue(securityManager.isUserInRole(request, "role1"));
    securityManager.removeUser("username");
    assertFalse(securityManager.isUserInRole(request, "role1"));
}
 
Example #7
Source File: ExternalProgramLoginModule.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean login() throws LoginException {
	readOptions();
	getNameAndPassword();
	callExternalProgram();
	success = true;
	user = new UserPrincipal(username);
	return true;
}
 
Example #8
Source File: AccountControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldFailOnValidationTryingToRegisterNewAccount() throws Exception {

	final User user = new User();
	user.setUsername("t");

	String json = mapper.writeValueAsString(user);

	mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isBadRequest());
}
 
Example #9
Source File: AccountControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldRegisterNewAccount() throws Exception {

	final User user = new User();
	user.setUsername("test");
	user.setPassword("password");

	String json = mapper.writeValueAsString(user);
	System.out.println(json);
	mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isOk());
}
 
Example #10
Source File: AccountControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldFailOnValidationTryingToSaveCurrentAccount() throws Exception {

	final Account account = new Account();
	account.setName("test");

	String json = mapper.writeValueAsString(account);

	mockMvc.perform(put("/current").principal(new UserPrincipal(account.getName())).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isBadRequest());
}
 
Example #11
Source File: AccountControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldSaveCurrentAccount() throws Exception {

	Saving saving = new Saving();
	saving.setAmount(new BigDecimal(1500));
	saving.setCurrency(Currency.USD);
	saving.setInterest(new BigDecimal("3.32"));
	saving.setDeposit(true);
	saving.setCapitalization(false);

	Item grocery = new Item();
	grocery.setTitle("Grocery");
	grocery.setAmount(new BigDecimal(10));
	grocery.setCurrency(Currency.USD);
	grocery.setPeriod(TimePeriod.DAY);
	grocery.setIcon("meal");

	Item salary = new Item();
	salary.setTitle("Salary");
	salary.setAmount(new BigDecimal(9100));
	salary.setCurrency(Currency.USD);
	salary.setPeriod(TimePeriod.MONTH);
	salary.setIcon("wallet");

	final Account account = new Account();
	account.setName("test");
	account.setNote("test note");
	account.setLastSeen(new Date());
	account.setSaving(saving);
	account.setExpenses(ImmutableList.of(grocery));
	account.setIncomes(ImmutableList.of(salary));

	String json = mapper.writeValueAsString(account);

	mockMvc.perform(put("/current").principal(new UserPrincipal(account.getName())).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isOk());
}
 
Example #12
Source File: AccountControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentAccount() throws Exception {

	final Account account = new Account();
	account.setName("test");

	when(accountService.findByName(account.getName())).thenReturn(account);

	mockMvc.perform(get("/current").principal(new UserPrincipal(account.getName())))
			.andExpect(jsonPath("$.name").value(account.getName()))
			.andExpect(status().isOk());
}
 
Example #13
Source File: StatisticsControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentAccountStatistics() throws Exception {

	final DataPoint dataPoint = new DataPoint();
	dataPoint.setId(new DataPointId("test", new Date()));

	when(statisticsService.findByAccountName(dataPoint.getId().getAccount()))
			.thenReturn(ImmutableList.of(dataPoint));

	mockMvc.perform(get("/current").principal(new UserPrincipal(dataPoint.getId().getAccount())))
			.andExpect(jsonPath("$[0].id.account").value(dataPoint.getId().getAccount()))
			.andExpect(status().isOk());
}
 
Example #14
Source File: StatisticsControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldGetStatisticsByAccountName() throws Exception {

	final DataPoint dataPoint = new DataPoint();
	dataPoint.setId(new DataPointId("test", new Date()));

	when(statisticsService.findByAccountName(dataPoint.getId().getAccount()))
			.thenReturn(ImmutableList.of(dataPoint));

	mockMvc.perform(get("/test").principal(new UserPrincipal(dataPoint.getId().getAccount())))
			.andExpect(jsonPath("$[0].id.account").value(dataPoint.getId().getAccount()))
			.andExpect(status().isOk());
}
 
Example #15
Source File: RecipientControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentRecipientSettings() throws Exception {

	Recipient recipient = getStubRecipient();
	when(recipientService.findByAccountName(recipient.getAccountName())).thenReturn(recipient);

	mockMvc.perform(get("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())))
			.andExpect(jsonPath("$.accountName").value(recipient.getAccountName()))
			.andExpect(status().isOk());
}
 
Example #16
Source File: RecipientControllerTest.java    From piggymetrics with MIT License 5 votes vote down vote up
@Test
public void shouldSaveCurrentRecipientSettings() throws Exception {

	Recipient recipient = getStubRecipient();
	String json = mapper.writeValueAsString(recipient);

	mockMvc.perform(put("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isOk());
}
 
Example #17
Source File: UserControllerTest.java    From microservice-skeleton with MIT License 4 votes vote down vote up
@Test
public void shouldReturnCurrentUser() throws Exception {
    mockMvc.perform(get("/users/current").principal(new UserPrincipal("test")))
            .andExpect(jsonPath("$.name").value("test"))
            .andExpect(status().isOk());
}
 
Example #18
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 #19
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);
}
 
Example #20
Source File: MqttHttp.java    From mithqtt with Apache License 2.0 4 votes vote down vote up
@Override
public void run(MqttHttpConfiguration configuration, Environment environment) throws Exception {
    // validator
    logger.debug("Initializing validator ...");
    Validator validator = new Validator(configuration);

    // storage
    SyncStorage storage = (SyncStorage) Class.forName(storageConfig.getString("storage.sync.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing storage storage ...");
            storage.init(storageConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying storage storage ...");
            storage.destroy();
        }
    });

    // authenticator
    Authenticator authenticator = (Authenticator) Class.forName(authenticatorConfig.getString("authenticator.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing authenticator ...");
            authenticator.init(authenticatorConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying authenticator ...");
            authenticator.destroy();
        }
    });

    // cluster
    Cluster cluster = (Cluster) Class.forName(clusterConfig.getString("cluster.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing cluster ...");
            cluster.init(clusterConfig, null);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying cluster ...");
            cluster.destroy();
        }
    });

    // OAuth
    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<UserPrincipal>()
                    .setAuthenticator(new OAuthAuthenticator(authenticator))
                    .setAuthorizer(new PermitAllAuthorizer<>())
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(UserPrincipal.class));

    // register resources
    environment.jersey().register(new MqttPublishResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttSubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttUnsubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));

    // config jackson
    environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    environment.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    environment.getObjectMapper().configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
 
Example #21
Source File: OAuthAuthenticator.java    From mithqtt with Apache License 2.0 3 votes vote down vote up
/**
 * Authenticate
 * <p>
 * The DropWizard OAuthFactory enables OAuth2 bearer-token authentication,
 * and requires an authenticator which takes an instance of String
 * Also the OAuthFactory needs to be parameterized with the type of the principal the authenticator produces.
 *
 * @param credentials OAuth2 bearer-token
 * @return User Id
 */
@Override
public Optional<UserPrincipal> authenticate(String credentials) throws AuthenticationException {
    if (StringUtils.isBlank(credentials)) {
        return Optional.empty();
    }
    // validate token
    String u = this.authenticator.oauth(credentials);
    return StringUtils.isBlank(u) ? Optional.empty() : Optional.of(new UserPrincipal(u));
}