Bearer Token Authentication: differenze tra le versioni

Da Webmobili Wiki.
Creata pagina con "Per implementarla installare i seguenti '''pacchetti nuGet''' * Owin * Microsoft.Owin * Microsoft.Owin.Security * Microsoft.Owin.Security.OAuth * Microsoft.Owin.Host.SystemWeb..."
 
Nessun oggetto della modifica
Riga 8: Riga 8:
Successivamente è necessario inserire un nuovo elemento nella ROOT del progetto<br/>
Successivamente è necessario inserire un nuovo elemento nella ROOT del progetto<br/>
<code>Visual c# => Web => General => OWIN Startup class</code><br/>
<code>Visual c# => Web => General => OWIN Startup class</code><br/>
che crea un file <code>Startup.cs</code>
che crea un file <code>Startup.cs</code><br/><br/>
 
Ora implementiamo un '''Provider''' che si occupa della creazione/restituzione/validazione del bearer token.<br/>
Si tratta dell'implementazione dell'interfaccia <code>OAuthAuthorizationServerProvider</code> di Microsoft.Owin.Security.OAuth<br/>
es.
<syntaxhighlight lang="c#">
public class BearerAuthorizationServerProvider : OAuthAuthorizationServerProvider {
 
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
context.Validated(); //
}
 
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
if (context.UserName != ConfigurationManager.AppSettings["bearerUsername"].ToString() ||
context.Password != ConfigurationManager.AppSettings["bearerPassword"].ToString()) {
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
else {
// Questa parte non ci è molto chiara, ma funziona. In questo modo viene creato un utente "completo" di authentication type.
// Usando solo new GenericIdentity(userName) restituiva un errore di token non autorizzato
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
// Construct a GenericIdentity object based on the current Windows
// identity name and authentication type.
string authenticationType = windowsIdentity.AuthenticationType;
string userName = windowsIdentity.Name;
GenericIdentity authenticatedGenericIdentity = new GenericIdentity(userName, authenticationType);
 
context.Validated(authenticatedGenericIdentity);
}
}
}
</syntaxhighlight><br/>
 
Per registrare l'interfaccia all'applicazione è necessario modificare come segue il file <code>Startup.cs</code> prima creato.
<syntaxhighlight lang="c#">
public class Startup {
 
public void ConfigureOAuth(IAppBuilder app) {
var myProvider = new BearerAuthorizationServerProvider();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions {
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = myProvider
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
 
public void Configuration(IAppBuilder app) {
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
ConfigureOAuth(app);
}
}
</syntaxhighlight>

Versione delle 16:19, 6 ott 2021

Per implementarla installare i seguenti pacchetti nuGet

  • Owin
  • Microsoft.Owin
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Host.SystemWeb

Successivamente è necessario inserire un nuovo elemento nella ROOT del progetto
Visual c# => Web => General => OWIN Startup class
che crea un file Startup.cs

Ora implementiamo un Provider che si occupa della creazione/restituzione/validazione del bearer token.
Si tratta dell'implementazione dell'interfaccia OAuthAuthorizationServerProvider di Microsoft.Owin.Security.OAuth
es.

public class BearerAuthorizationServerProvider : OAuthAuthorizationServerProvider {

	public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
		context.Validated(); // 
	}

	public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
		if (context.UserName != ConfigurationManager.AppSettings["bearerUsername"].ToString() ||
			context.Password != ConfigurationManager.AppSettings["bearerPassword"].ToString()) {
			context.SetError("invalid_grant", "The user name or password is incorrect.");
			return;
		}
		else {
		
			// Questa parte non ci è molto chiara, ma funziona. In questo modo viene creato un utente "completo" di authentication type.
			// Usando solo new GenericIdentity(userName) restituiva un errore di token non autorizzato
			WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
			// Construct a GenericIdentity object based on the current Windows
			// identity name and authentication type.
			string authenticationType = windowsIdentity.AuthenticationType;
			string userName = windowsIdentity.Name;
			GenericIdentity authenticatedGenericIdentity = new GenericIdentity(userName, authenticationType);

			context.Validated(authenticatedGenericIdentity);
		}
	}
}


Per registrare l'interfaccia all'applicazione è necessario modificare come segue il file Startup.cs prima creato.

public class Startup {

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

	public void Configuration(IAppBuilder app) {
		// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
		ConfigureOAuth(app);
	}
}