Posted on

Token based authentication in ASP.NET Web API

Token based authentication

Nella “Token based authentication”, l’applicazione client invia prima una richiesta all’endpoint del server di autenticazione con le credenziali dell’utente; se il nome utente e la password sono corretti, il server di autenticazione invia un token al client come risposta. Questo token contiene dati sufficienti per identificare un determinato utente e un tempo di scadenza. L’applicazione client utilizza quindi il token per accedere alle risorse nelle richieste successive fino a quando il token risulta ancora valido (non scaduto).

Classe per validare le richieste del client

Aggiungete una classe come questa :

using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;


namespace Mysite.Helpers
{
    public class MysiteAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); // 
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            var user = await userManager.FindAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
            OAuthDefaults.AuthenticationType);

            context.Validated(oAuthIdentity);
        }
    }
}

Per attivare questa classe andate nel file App_Start/Startup.Auth.cs e aggiungete alla fine del metodo ConfigureAuth questo codice

var myProvider = new  MysiteAuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

In cui si definisce il link http://mysite/token che restituisce un token di durata 1 giorno.

Dovrete aggiungere nel file il riferimento

using Microsoft.Owin.Security.OAuth;

E’ necessario aggiungere un metodo all’autenticazione. Andate nel file IdentityModel.cs e aggiungete questo metodo :

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager,
            string authenticationType)
        {
           var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
           return userIdentity;
        }

TEST CON POSTMAN

Per testare il tutto facilmente potete usare Postman .

Dovrete creare con Postman una chiamata post sul vostro link http://mysite/token. Nell’headers inserite la dicitura che vedete in figura :

Nel Body inserite il tipo di autneticazione (password) il vostro username e la vostra password.

Spingete “Send”. Se tutto ha funzionato riceverete il token

Utilizzo del Token

Una volta che il client ha ricevuto il token lo può utilizzare per tutte le successive operazioni senza dover passare lo username e la password: va passato solo il token che contiene queste informazioni. Facciamo una prova, creando un metodo che richiede autenticazione all’interno di un controller :

using System;
using System.Web.Http;

namespace MySite.Controllers
{
    public class SampleController : ApiController
    {
       [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok("Hello " + identity.Name);
        }
   }
}

Usando postman, fate una chiamata GET al link : http://MySite/api/Sample/GetForAuhenticate

Dovrete passare al link il token che avete ottenuto qualche istante prima (nel nostro esempio è valido per 1 giorno). Per farlo in postman aggiungete la chiave Authorization con valore la parola Bearer seguita dal token.

THE END

Posted on

add Web API to an asp.net mvc site

Install the Web API Client Libraries

Use NuGet Package Manager to install the Web API Client Libraries package :

  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.WebHost

Define a Web API Routing Configuration

Add App_Start\WebApiConfig.cs

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    }
}

Register the WebAPI Routing Configuration

If you added a new WebApiConfig.cs file, you need to register that on your Web Application’s main configuration class.

Import namespace System.Web.Http in Global.asax.cs.

Add this line before the registration of your classic routing

//api routing (before)
GlobalConfiguration.Configure(WebApiConfig.Register);
//existing normal route
RouteConfig.RegisterRoutes(RouteTable.Routes);

Create a sample Web API Controller

Create a new controller

using System;
using System.Web.Http;

namespace MySite.Controllers
{
    public class SampleController : ApiController
    {
       [HttpGet]
       public String Test()
       {
         return "Hello World!";
       }
   }
}

Based on the api routing you should call this method in your browser using

http://MySite/api/Sample/Test

with this result

<string xmlns=”http://schemas.microsoft.com/2003/10/Serialization/”>Hello World!</string>

Posted on

Android java app with notification from asp.net mvc using firebase cloud messaging – part 3

Notification service in Android

Now we need to create in Android the service able to manage the notification incoming from firebase and to show these to user. Follow this usefull article Working easily with FCM push notifications in Android. You’ll have a class like this.

package com.mycompany.myfirstapp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import androidx.core.app.NotificationManagerCompat;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

//is the class that we can find in the manifest as a service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "MsgFirebaseServ";

    @Override


    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String title = "";
        String body = "";
        String objectId = "";
        String objectType = "";

        if (remoteMessage.getData() != null) {
            title = remoteMessage.getData().get("title");
            body = remoteMessage.getData().get("body");
            objectId = remoteMessage.getData().get("object_id");
            objectType = remoteMessage.getData().get("objectType");
        }

        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setContentText(body)
                .build();
        NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
        manager.notify(/*notification id*/0, notification);
    }
}

Run your app on your device

Follow this instruction : https://developer.android.com/training/basics/firstapp/running-app

First test using your app in your device

  • Run the app on your device or emulator. The app should had created a new register id for the device and send it to asp.net mvc site. Now the device is registered.
  • Open Firebase console, go down in the menu on the left. Open Cloud Messaging session : you should find the possibility to send notification to your device starting from this page. So you can test correct developing of above class.

Send notification from asp.net mvc to firebase

For backend developers. You should create a class to manage notification to firebase. Follow the article Firebase push notifications using a .NET Backend to prepare a class to manage the notification to Firebase.

Then prepare your notification test task in a controller. Something like this :

        public Task<bool> NoteAsync()
        {
            var device = db.RegisteredDevices.Where(d => d.ENABLED == true);
            string[] da = new string[device.Count()];
            int i = 0;
            foreach (RegDevice r in device)
            {
                da[i] = r.ID;
                i++;     
            }
            string serverkey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            return FCMPushNotification.SendPushNotification(da,serverkey,"Title","body");
        }

Firebase messaging, where to get Server Key?

Click the Settings (Cog wheel) icon next to your project name at the top of the new Firebase Console, as per screenshot below:

  1. Click Project settings.
  2. Click on the Cloud Messaging tab.


Final test

Call the asp.net mvc method created. You should see a notification in 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 2

Links



Posted on

ASP.NET MVC: DEPLOY OF A SITE

Visual Studio allows us to publish our web site on a web server in the lan (intranet) or on an external web server, for example hosted on Azure.

In the situation of a server on the lan, you have created, through IIS, a site that resides on a certain directory, empty now, on a web server. Otherwise you have already prepared an external site.

In Visual Studio, in the right panel called “Solution Explorer” we click with the right mouse button on our project and select the “Publish” option. The “Publish” window: there are, on the left, the fourth step to do for publication.

Profile

Go to the drop down menu at the top center and choose “New Custom Profile”. Invent the name of this profile. Once inserted, you will go directly to the next step.

Connection with “Web Deploy”

Publish Metod : choose “Web Deploy”  whether you publish your site on a server on the lan, both in an external server.

Server (web server in lan) : http://myserver

Server (external, es Azure): mysite.azurewebsites.net:443

Site name (web server in lan) : name of the directory in which it is to be the site

Site name (external, es Azure) : es. mysite

User Name e Password (web server in lan) : put a administrator user of the server machine. If the machine is in a domain,  use a local administrator.

User Name e Password (esterno) : ftp user

Destination Url : web site address. es : http://……………..

Settings

In this tab the program reads from we.config the database connection strings. If your target site database is different, you need to specify the right connection. The publication will replace the target strings to the source strings. We will see later that there is a method to insert in the web.config further changes to the web.config of origin.

Preview

Here you can see the files that will be sent to the destination that is the new files or changed since the last submission. And you can publish your site!


web.config configuration

Our destination website may have other special features, specified in web.config, different from the starting site, as well as database connection strings. We can create a specific web.config for each deployment.

Position  the mouse on the project. In the “Properties”, find the directory “PublishProfiles” which contains previously saved data. Here you will find a .pubxml files for each of the deployment that you have created. Go to the file you need, push the right mouse button and select “Add Config Transform”.

If you go in the web.config you will see that there is an additional file named as your deployment. Let’s see some examples of what you can do with the tag that you set within the <configuration>

<connectionStrings>
 <add name="MyDB"
 connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
 xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
 </connectionStrings>

this stringa substitutes (xdt:Transform=”SetAttributes”) the attributes of the tag named  (xdt:Locator=”Match(name)) “MyDB” with these.

<appSettings><add key="myemail" value="info@contoso.com" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/></appSettings>

this stringa substitutes the attributes (xdt:Transform=”SetAttributes”) of the tag with key (xdt:Locator=”Match(key)) “myemai” with these.

<system.net>
 <mailSettings xdt:Transform="Replace">
 <smtp deliveryMethod="Network" ........................
 </smtp>
 </mailSettings>
 </system.net>

This string transform (xdt:Transform=”Replace”) entire tag mailSettings and its content.

Posted on

ASP.NET MVC EMAIL FROM SITE AND FORGOT PASSWORD

Our site needs to send emails to its users, for example when the user forgets the password. To do this comes to the rescue System.Net.Mail.SmtpClient class.

This class automatically uses the SMTP server settings stored in the Web.config file. You just have to add to that file the following tags inside the configuration tag:

<system.net>
 <mailSettings>
 <smtp deliveryMethod="Network" from="mail_from">
 <network host="my_smtp_server" port="my_smtp_server_port" userName="user_name_smtp" password="password" clientDomain="my_domain" />
 </smtp>
 </mailSettings>
 </system.net>

FORGOT DIMENTICATA

In the view Account/Login , you can see, bottom, on the left, the link to Account/ForgotPassword that is the page where the user can reset his password.

In the  controller Account, in the action post  “ForgotPassword” you make operational, removing them as a comment, the lines of code dedicated to password recovery.

In the file IdentityConfig.cs, in the function

public Task SendAsync(IdentityMessage message)

and replaced to the line

return Task.FromResult(0);

with the following lines of code

var sentFrom = "myemail@mydomain.com"
 //
 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
 //
 client.EnableSsl = false;

// Create the message:
 var mail =
 new System.Net.Mail.MailMessage(sentFrom, message.Destination);

mail.Subject = message.Subject;
 mail.Body = message.Body;
 mail.IsBodyHtml = true;

// Send:
 return client.SendMailAsync(mail);

You have activated the password recovery