Mobile first server 7.1 - Unsubscribe from Push Notification (Unicast Notification) - ibm-mobilefirst

We are making an hybrid application Using Mobile First Platform. For push notification we will be using Unicast notifications. I could not find any documentation regarding unsubscription. Can any one help me to know how can I unsubscribe user from push notification in Unicast Notification scenario.

Check the official documentation here, It says:
The userId(s) must be the user IDs that were used to subscribe to the push notification event source.
Which suggests that unicast notifications uses a the same event-source subscription/unsubscription mechanisms, check the official documentation here for how to unsubscribe from an event source.

I found the way to unsubscribe from Unicast Notification. Not sure if this is the right way but it works for me. I used REST API Runtime Services
The REST API for Push in the MobileFirst runtime environment enables back-end server applications that were deployed outside of the MobileFirst Server to access Push functions from a REST API endpoint.
Thought it is designed for backend server it works for me.
String token = getToken("unregister-device");
First get the token the details about how to get the token is here
Once you get the token then implement the rest client check the documentation here
Sample code.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpDelete postRequest = new HttpDelete("http://localhost:10080/MyProject/imfpush/v1/apps/MyMobileApp/devices/12121-1212121-121212-12121");
postRequest.addHeader("Content-Type", "application/json");
postRequest.addHeader("Authorization", "Bearer "+token);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 204) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

Related

Sending a message to Discord channel via POST request results in code 401

I was searching for the easiest way to send a message to Discord channel from Chrome extension.
I have a Discord app and corresponding bot registered on Discord Developer Portal. I have bot token there.
Found this SO question. Tried the code Tobyhn suggested and ended up with this:
var token = "my bot token here";
var channel_id = "my channel id here";
var channel_url = `https://discord.com/api/v8/channels/${channel_id}/messages`
request = new XMLHttpRequest();
request.withCredentials = true;
request.open("POST", channel_url);
request.setRequestHeader("authorization", token);
request.setRequestHeader("accept", "/");
request.setRequestHeader("authority", "discord.com");
request.setRequestHeader("content-type", "application/json");
request.send(JSON.stringify({ content: message }));
Code is just placed right in background script.
Chrome is run with flags --disable-web-security --disable-gpu --user-data-dir=~\chromeTemp" to avoid CORS checks.
Also I'm absolutely sure that bot is given Administrator privileges on Discord server that channel is at, so writing a message must be possible.
However, upon execution server responds with code 401:
code: 0
message: "401: Unauthorized"
I also tried to send the same request from Yet Another Rest Client and result was the same.
How can I change the request for it to successfully authorize and send the message?
To provide additional context: the very same bot successfully sends messages to various channels on the same server when I use it with help of discord.js library.
I've also read this thread, but the solution there seems not to be found and nothing said there seems to be applicable to my situation.
Many thanks in advance!
You need to specify Token Type
Example Bot Token Authorization Header
Authorization: Bot MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs
Example Bearer Token Authorization Header
Authorization: Bearer CZhtkLDpNYXgPH9Ml6shqh2OwykChw
So Change request.setRequestHeader("authorization", token);
with request.setRequestHeader("authorization", Bot ${token}); if you are using bot token
https://discord.com/developers/docs/reference
No, they are not real tokens, I get them from their documentation.

SignalR Core JS Client not passing Authorisation headrs on "Upgrade " Request

I Have to implement a push notification service using ASP .Net Core. as obvious choice is to use SignalR Core.
Our platform setup is using Azure App gateway and it is configured to not allow unauthenticated requests.
We have setup WebSockets communication with SignalR.
Under the hood , SignalR Core follows these steps:
POS ../negociate -> OK with hub_token and supported transport
GET (sends Upgrade header and WebSockets token)../Hub?id={hub_token} -? fail
when investigating why the step 2 does not upgrade the connection to a WebSocket connection , I have noticed that the GET request is missing Authorization header. Obviously AG block this request and doesn't even get to the API.
I have tried manually to make a "handshake" with postman.
the above steps :
OK
included Authorization JWT header -> result 101 ,and Fiddler confirm the connection is opened.
I have researched the documentation and found that Authorization headers are not supported.
did anyone tried any workaround ? hen is the next release of the #aspnet/signalr client?
Did you specified the accessTokenFactory?
let connection = new signalR.HubConnectionBuilder()
.withUrl("/myhub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
More info here.
so the final resolution is:
that in browsers is a limitation for sending JWT header along with HTTP 101 UPGRADE

Push notification support in Twilio IOS sdk

I'm trying to get push notifications on an app that's using Twilio IP Messaging. After following the instructions on twilio guides.
The AppDelegate functions to register for remote notifications is working well - the iOS devices successfully provides the device token to the Twilio Client. However, the TwilioIPMessagingClient gives no indication of success or failure while registering the token.I have used delegates also for that Moreover, I don't get any sign of push notifications when messages get sent.
I have checked logs also where I can see the correct logs:
TNNotificationClient | Starting registration..., id: <....>
TNRegTransport | Creating registration: apn - <....>
TNRegTransport | Registration is created, location: https://ers.us1.twilio.com/v1/registrations/<...>
Where exactly I'm missing? One hint I got to know after much research that in server PHP app, I need to enable push on IPMesaging services client becuase its disabled by default. If yes, where exactly or in which .php file I have to enable it?
Reference:
https://www.twilio.com/docs/api/ip-messaging/guides/push-notification-configuration
Someone else recently solved this problem realizing that they had not set the New Message notification type to be explicitly enabled as follows from the PHP example:
// Update the service webhooks
$service = $client->services->get("YOUR_IP_MESSAGING_SERVICE_SID");
$response = $service->update(array(
"Notifications.NewMessage.Enabled" => "true",
"Notifications.NewMessage.Template" => "A New message in ${CHANNEL} from ${USER}: ${MESSAGE}",
));
?>
Would this solve it for you?

Servicestack Windows Universal Social Authentication

I am trying to implement social authentication from a c# client within a windows universal 8.1 app. When I post to the auth provider .../googleoauth for example the client fails. Fiddler is showing a 302 redirect so the deserialization fails n the response. The authentication flow works if I use a browser so I think everything is configured correctly, but of course could have missed something. If anyone has any insight or an example using social authentication providers from a c# client that would be much appreciated.
ian
The OAuth flow requires a browser to work in order to redirect the user to the remote OAuth website where they can approve access. So you'll need to launch the url in a WebView then capture the Session cookies after the user approves your application and is redirected back to your website.
The TechStacks Auth Example demonstrates this strategy using Xamarin.Auth component for Xamarin.Android.
Just in case anyone else was looking for a sample in UWP. This seems to be working for me. The CreateCookieContainer method for the most part simply loops through the cookies and adds them to a new container that is returned. Thanks #mythz again for the awesome work and support in ServiceStack
// Grab auth cookies from callback uri
var cookies = _httpFilter.CookieManager.GetCookies(uri);
var authCookies = cookies.AsEnumerable().Where(x => new[] {"ss-id", "ss-pid", "ss-opt"}.Contains(x.Name))
.Select(x => new Cookie(x.Name, x.Value, x.Path, x.Domain)).ToArray();
string sessionId = null;
var cookieJar = CreateCookieContainer(authCookies, uri, ref sessionId);
// Store the tokens for autologin
await DataServiceFactory.Instance.StoreSingletonSetAsync(authCookies);
// Set auth on the current client
_serviceClient.CookieContainer = cookieJar;
_serviceClient.SessionId = sessionId;

Client Authentication when using Service Bus for Windows Server

I'm currently working on a project where we use the Service Bus for Windows Server queues and topics for handling messaging between clients and server. Currently I'm looking into how to handle authentication of the clients and believe we need to use SAS. The clients communicating with the queues can be using both rest and the .net api. I have tried to find resources on best practices especially on how to handle token generation and distribution. For example should we create a service for this that the calling client can connect to providing the access key which would then generate a token returned to the client. Ideas and suggestions would be greatly appreciated.
/Thanks
I would recommend using the WindowsTokenProvider and a Windows user account.
First add a valid Windows user to the Bus with Send permissions on your queue/topic. (You can do this in code or via service bus explorer.)
Then for the Rest API client authentication over Http - You need to post over a valid UserName/Pwd to the STS then add the resulting token to the authorization header of the actual post to the queue.
You can see how to do this here...
For the .Net client over TCP -
Run your client as the same valid windows user, and then call the STS with these implicit credentials by using the TokenProvider.CreateWindowsTokenProvider.
3.1 If you are using the NetMessagingBinding for your client (WCF) then do the following:
var uri = new Uri(string.Format("https://{0}:9355/ServiceBusDefaultNamespace", serverName));
var uris = new List<Uri> {uri};
var securityBehavior = new TransportClientEndpointBehavior
{
TokenProvider = TokenProvider.CreateWindowsTokenProvider(uris)
};
var endpoint = new ServiceEndpoint(contract, new NetMessagingBinding(), new EndpointAddress(serviceBusEndpointAddress));
endpoint.Behaviors.Add(securityBehavior);
3.2 NB - The code above will take the implicit credentials of the current principal and pass them across. However, you can explicitly pass in credentials like this:
var securityBehavior = new TransportClientEndpointBehavior
{
TokenProvider = TokenProvider.CreateWindowsTokenProvider(uris, new NetworkCredential("myUser", "myPassword"))
};
3.3 Or if you just use the plain .NetClient you can do the same like this:
var uri = new Uri(string.Format("https://{0}:9355/ServiceBusDefaultNamespace", serverName));
var uris = new List<Uri> {defaultUri};
var messagingFactorySettings = new MessagingFactorySettings();
messagingFactorySettings.TokenProvider =
TokenProvider.CreateWindowsTokenProvider(uris, new
NetworkCredential("myUser", "myPassword"));
.....
var factory = MessagingFactory.Create("endpoint", messagingFactorySettings);