In this scenario we looking to send the device registration id to a server with user data to save it in our database.
Token based authentication in ASP.NET Web API
For backend developers. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients. Follow the following article in order to implement Token based authentication using ASP.NET Web API 2. (Part 1 : Token based authentication in ASP.NET Web API)
To register the device you need a method like this
[HttpPost]
public HttpResponseMessage Register(string key)
{
var identity = (ClaimsIdentity)User.Identity;
string message = "";
if (!string.IsNullOrEmpty(key))
{
var userid = identity.GetUserId();
RegDevice device = db.RegisteredDevices.Where(d => d.ID == key &&
d.USER == userid).FirstOrDefault();
if (device == null)
{
device = new RegDevice();
device.ID = key;
device.USER = userid;
db.RegisteredDevices.Add(device);
if (db.SaveChanges() > 0)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
message = Vocabolario.ErrorInTemporaryStorage;
//System.Diagnostics.Debug.WriteLine("PostServerLog. erore" +
message);
}
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "value");
response.Content = new StringContent(message, Encoding.Unicode);
return response;
}
Bearer authentication on Java
For frontend developers. To authenticated in a asp.net mvc site, first of all you have to generate the token using the username and the password. The token will conserve all the user’s data more the validation time. We will use this token to talk to our server.
Getting a token is not a goal per se. It’s a necessary step to call a protected API. The token needs to be used to access a Web API. The way to do it is by setting the Authorization header to be “Bearer”, followed by a space, followed by the access token.
To generate the token you should use something like this :
package com.mycompany.myfirstapp;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.io.InputStream;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONObject;
import org.apache.wink.json4j.JSONException;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import javax.net.ssl.SSLPeerUnverifiedException;
public class MyServer {
private final static String BASE_URL = "https://www.mysite.com";
private final static String TOKEN_ENDPOINT = BASE_URL + "/token";
private final static String REGDEVICE_ENDPOINT = BASE_URL + "/api/Account/Register";
//pass username and password in this example
public static String getToken(String user, String pwd) throws IOException, JSONException {
byte[] postData = getRequestBodyForAccessToken(user,pwd);
int postDataLength = postData.length;
URL url = new URL(TOKEN_ENDPOINT);
HttpsURLConnection requestConn = (HttpsURLConnection) url.openConnection();
requestConn.setRequestMethod("POST");
requestConn.setDoOutput(true);
requestConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (DataOutputStream dos = new DataOutputStream(requestConn.getOutputStream())) {
dos.write(postData);
}
if (requestConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
if (requestConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String serverURL = requestConn.getHeaderField("Location");
System.err.println("Set the value of the server path to: " + serverURL);
}
System.err.println("Error in obtaining an access token. " +
requestConn.getResponseMessage());
}
String accessToken;
try (InputStream tokenStream = requestConn.getInputStream()) {
JSONObject tokenRes = new JSONObject(tokenStream);
accessToken = (String) tokenRes.get("access_token");
}
return accessToken;
}
public static void RegisterNewDevice(String deviceKey, String atoken)
{
StringBuilder urlBuilder = new StringBuilder(REGDEVICE_ENDPOINT);
urlBuilder.append("&key=").append(deviceKey);
String pathWithQueryParams = urlBuilder.toString();
InputStream restRegApiStream = null;
try {
HttpsURLConnection restRegApiConn = getRestApiConnection(pathWithQueryParams);
addAuthenticationHeader(restRegApiConnn, atoken);
restRegApiConn.setRequestMethod("POST");
if (restRegApiConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
if (restRegApiConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
if (restRegApiConn.getHeaderField("www-authenticate").contains("invalid_token")) {
}
} else if (restRegApiConn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
}
} else {
restRegApiStream = restRegApiConn.getInputStream();
}
}
catch(Exception ex)
{
}
}
private static HttpsURLConnection getRestApiConnection(String apiCall) throws IOException {
URL restApiUrl = new URL(apiCall);
HttpsURLConnection restApiURLConnection = (HttpsURLConnection) restApiUrl.openConnection();
return restApiURLConnection;
}
private static void addAuthenticationHeader(HttpsURLConnection restApiURLConnection, String t)
{
restApiURLConnection.setRequestProperty("Authorization", "Bearer " + t);
}
/**
* Get the request body to be used for the POST request when requesting an access token.
*/
private static byte[] getRequestBodyForAccessToken(String user, String pwd) {
StringBuilder sb = new StringBuilder("grant_type=password");
sb.append("&username=")
.append(user)
.append("&password=")
.append(pwd);
return sb.toString().getBytes(StandardCharsets.UTF_8);
}
private static void print_https_cert(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : "
+ cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : "
+ cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
private static void print_content(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
So now you have registered the device on the server. It’s time to send notification to your device
Android java app with notification from asp.net mvc using firebase cloud messaging – part 1
Android java app with notification from asp.net mvc using firebase cloud messaging – part 3
Links
- add firebase to your android project official
- Firebase console
- Setup a firebase cloud messaging client app on Android
- Part 1 : Token based authentication in ASP.NET Web API
- Firebase push notifications using a .NET Backend
- Firebase messaging, where to get Server Key?
- Java HttpsURLConnection example
- Java HttpsURLConnection example 2
- Working easily with FCM push notifications in Android
- Run your app on your device