<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Gianlucb</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/gianlucb/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/gianlucb/feed.xml</link>
    <description>Blogging about Distributed Services, Azure and Universal App</description>
    <lastBuildDate>Mon, 19 Feb 2018 15:11:11 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Azure AD, Scope-based authorization</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/azure-ad-scope-based-authorization</link>
      <pubDate>Tue, 05 Dec 2017 10:37:41 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=295</guid>
      <description><![CDATA["Hello World!"

Continuing the customization of the basic two tiers scenario introduced in my...]]></description>
      <content:encoded><![CDATA["Hello World!"

Continuing the customization of the basic two tiers scenario introduced in my previous posts, I would like to talk about <b>scopes</b>. OAuth2 defines the concept of <b>scope </b>as a "list of space-delimited, case-sensitive strings" that specifies the scope of the access request. These <b>scopes</b> can be used by a target application to allow or deny the access to its resources. Hence, with the <b>scopes</b> we can fine-tune the API access based on the caller access token.

To make it simple:
<ol>
 	<li>The target application (Api) defines which scopes supports (i.e.: "scopeA", "scopeB” ...)</li>
 	<li>The client application (FrontEnd) specifies which scopes wants during the access token request **</li>
 	<li>The authentication server (Azure AD) replies with an access token that contains a field (<b>scp</b>) with all the valid scopes</li>
 	<li>The target application (Api) inspects the access token and takes the proper actions (allow, deny, redirect... etc)</li>
</ol>
Let's us start from the last step, the target application configuration.

From the point of view of the target application scopes are just strings (or better <b>claims</b>) part of the JWT token:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #a31515">"appid"</span>: <span style="color: #a31515">"6fa546d0-c2b8-4902-8415-a2b5bdc07472"</span>,
<span style="color: #a31515">"appidacr"</span>: <span style="color: #a31515">"0"</span>,
<span style="color: #a31515">"e_exp"</span>: 262800,
<span style="color: #a31515">"family_name"</span>: <span style="color: #a31515">"Standard"</span>,
<span style="color: #a31515">"given_name"</span>: <span style="color: #a31515">"User"</span>,
<span style="color: #a31515">"ipaddr"</span>: <span style="color: #a31515">"167.220.197.30"</span>,
<span style="color: #a31515">"name"</span>: <span style="color: #a31515">"user"</span>,
<span style="color: #a31515">"oid"</span>: <span style="color: #a31515">"703edbe8-0fcd-4d2e-8a99-c1ee78df2231"</span>,
<span style="color: #a31515;background-color: yellow">"scp"</span>: <span style="color: #a31515;background-color: yellow">"aad.scopeA aad.scopeB user_impersonation"</span>,
<span style="color: #a31515">"sub"</span>: <span style="color: #a31515">"4LSAbYQx-PYbh5LI98jS22dBq4AcFhy47CRmIXIbsAY"</span>,
<span style="color: #a31515">"tid"</span>: <span style="color: #a31515">"f7ad0521-ba5a-4622-bab1-8eae3e485430"</span>,
<span style="color: #a31515">"unique_name"</span>: <span style="color: #a31515">"user@bizspark7demooutlook.onmicrosoft.com"</span>,
<span style="color: #a31515">"upn"</span>: <span style="color: #a31515">"user@bizspark7demooutlook.onmicrosoft.com"</span>,
<span style="color: #a31515">"uti"</span>: <span style="color: #a31515">"VnxNhOlxE06flrDmAp4fAA"</span>,
<span style="color: #a31515">"ver"</span>: <span style="color: #a31515">"1.0"</span>
</pre>
</div>
In Asp.Net Core 2.0 we can easily integrate the scopes control defining authorization policies in the <i>Startup</i> class:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">services.AddAuthorization(options =&gt; {
   <span style="color: #008000">//custom scopes</span>
   options.AddPolicy(<span style="color: #a31515">"A"</span>, policyBuilder =&gt; policyBuilder.Requirements.Add(<span style="color: #0000ff">new</span> HasScopeRequirement(<span style="color: #a31515">"aad.scopeA"</span>)));
   options.AddPolicy(<span style="color: #a31515">"B"</span>, policyBuilder =&gt; policyBuilder.Requirements.Add(<span style="color: #0000ff">new</span> HasScopeRequirement(<span style="color: #a31515">"aad.scopeB"</span>)));
});
<span style="color: #008000">//HasScopeRequirement is a custom class</span>
</pre>
</div>
and then use such policies to control the API access:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">[<span style="color: #2b91af">Authorize</span>(Policy = <span style="color: #a31515">"A"</span>)]
<span style="color: #0000ff">public</span> <span style="color: #2b91af">string</span> GetWithScopeA()
{
   <span style="color: #0000ff">return</span> <span style="color: #a31515">"Hello from API (Scope A)"</span>;
}
 
[<span style="color: #2b91af">Authorize</span>(Policy = <span style="color: #a31515">"B"</span>)]
<span style="color: #0000ff">public</span> <span style="color: #2b91af">string</span> GetWithScopeB()
{
   <span style="color: #0000ff">return</span> <span style="color: #a31515">"Hello from API (Scope B)"</span>;
}
</pre>
</div>
In this manner we are allowing to access to our API only the users that have the right scopes in the access token, otherwise a <b>403 forbidden </b> message is returned.

So far so good. The next step is to tell Azure AD which are the supported scopes.

Technically speaking the scopes are just a JSON configuration in the application manifest (they are also called <b>OAuth2Permissions</b>):

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">{
    "adminConsentDescription": <span style="color: #a31515">"Allow the application access to scope B APIs"</span>,
    "adminConsentDisplayName": <span style="color: #a31515">"Scope B access"</span>,
    "id": <span style="color: #a31515">"b69ee3c9-c40d-4f2a-ac80-961cd1534e49"</span>,
    "isEnabled": <span style="color: #0000ff">true</span>,
    "type": <span style="color: #a31515">"User"</span>,
    "userConsentDescription": <span style="color: #a31515">"Allow the application access to scope B APIs"</span>,
    "userConsentDisplayName": <span style="color: #a31515">"Scope B access"</span>,
    "value": <span style="color: #a31515">"aad.scopeB"</span>
},
{
    "adminConsentDescription": <span style="color: #a31515">"Allow the application access to scope A APIs"</span>,
    "adminConsentDisplayName": <span style="color: #a31515">"Scope A access"</span>,
    "id": <span style="color: #a31515">"b69ee3c9-c40d-4f2a-ac80-961cd1534e48"</span>,
    "isEnabled": <span style="color: #0000ff">true</span>,
    "type": <span style="color: #a31515">"User"</span>,
    "userConsentDescription": <span style="color: #a31515">"Allow the application access to scope A APIs"</span>,
    "userConsentDisplayName": <span style="color: #a31515">"Scope A access"</span>,
    "value": <span style="color: #a31515">"aad.scopeA"</span>
}
</pre>
</div>
This is sufficient to create the scopes and exposes them to other applications in the same tenant. The scopes become visible in the "<b>Required Permissions</b>" settings of the other applications.

<a href="https://msdnshared.blob.core.windows.net/media/2017/12/delegated1.png"><img class="aligncenter size-full wp-image-317" alt="" src="https://msdnshared.blob.core.windows.net/media/2017/12/delegated1.png" width="635" height="200" /></a>

&nbsp;

We need to know that the scopes we select here are set as "<b>default</b>", that means every user will get such scopes in the access token, regardless of the client request.

A working example can be found <a href="https://github.com/gianlucb/Demo_AAD.2tiers/tree/scopes">here</a>

** The<b> V1.0</b> endpoint <b>does not honor</b> the scopes requested by the client; It always fills the "<b>scp</b>" field with the scopes defined in the portal. So, it is a static configuration: the scopes/permissions not selected in this tab cannot be requested by the caller.

*** The <strong>V2.0 </strong>endpoint <strong>honors</strong> the scopes in the client request as support <strong>dynamic</strong> and <strong>incremental</strong> <strong>consent</strong> pages

&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>Azure AD and Group-based authorization</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/azure-ad-and-group-based-authorization</link>
      <pubDate>Fri, 27 Oct 2017 12:14:12 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=285</guid>
      <description><![CDATA["Hello World!"

In my previous post I talked about how to use Azure AD to secure an Asp.Net Core...]]></description>
      <content:encoded><![CDATA["Hello World!"

In my previous <a href="https://blogs.msdn.microsoft.com/gianlucb/2017/10/04/access-an-azure-ad-secured-api-with-asp-net-core-2-0/">post</a> I talked about how to use Azure AD to secure an Asp.Net Core web API project. If we want to go further than just protect our web API, we can use <b>groups</b> to further customize the access. A typical example is to restrict the access only for users belonging to a specific group.
Each directory user can be part of one or more groups, so we can leverage this membership to allow or deny the access to our API based on the calling user attributes.
This is quite easy to implement, as Asp.Net Core uses the same authorization attribute we are used to:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">[Authorize(Policy = "Admins")]
<span style="color: #0000ff">public</span> IActionResult Get(<span style="color: #2b91af">int</span> id)
{
   <span style="color: #0000ff">return</span> Json(id);
}
</pre>
</div>
As you can see we need to use the <b>Policy</b> property to specify the rules that apply to the decorated member. This obviously requires defining our access policies (the rules) during the startup phase:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">services.AddAuthorization(options =&gt; {
   options.AddPolicy(<span style="color: #a31515">"Admins"</span>,
           policyBuilder =&gt; policyBuilder.RequireClaim(<span style="color: #a31515">"groups"</span>,
           <span style="color: #a31515">"f761047b-2f49-4d8e-903c-1234567890cc"</span>));
});
</pre>
</div>
We simply check the presence of a specific group in the claims set of the calling user. In other words, means the user must belong to this particular group in order to access. Note that we need to use the <strong>GUID</strong> of the group and not the group name as the <strong>access_token</strong> we receive from Azure Ad uses a list of <strong>GUIDs</strong> to describe the user membership.

Because by default the list of groups the user belongs to is not sent by Azure AD, we need to manually edit the manifest:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #a31515">"groupMembershipClaims"</span>:<span style="color: #a31515">"SecurityGroup"</span>
</pre>
</div>]]></content:encoded>
    </item>
    <item>
      <title>Access an Azure AD secured Api with Asp.Net Core 2.0</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/access-an-azure-ad-secured-api-with-asp-net-core-2-0</link>
      <pubDate>Wed, 04 Oct 2017 10:23:53 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=255</guid>
      <description><![CDATA[tl;dr

 	Register a new Web App in AAD for the Api
 	Register a new Web App in AAD for the...]]></description>
      <content:encoded><![CDATA[<b>tl;dr</b>
<ol>
 	<li>Register a new Web App in AAD for the Api</li>
 	<li>Register a new Web App in AAD for the FronEnd
<ol type="a">
 	<li>Add the permissions to access the Api app</li>
</ol>
</li>
 	<li>Configure the Web apps code with the authentication details as usual (ClientID, Client Secret, Audience Uri..etc..).</li>
 	<li>In Azure portal edit the FrontEnd manifest enabling the implicit flow:<em>
"<b>oauth2AllowImplicitFlow</b>": <strong>true</strong></em></li>
 	<li>To obtain an access token, in the FrontEnd app code, configure the <strong>OpenIdConnection</strong> options:
<ol type="a">
 	<li>set the response type to "<strong>token id_token</strong>"</li>
 	<li>specify the Api Application ID</li>
 	<li>enable the saving of the tokens in the HttpContext</li>
</ol>
</li>
</ol>
"Hello World!"

In my previous <a href="https://blogs.msdn.microsoft.com/gianlucb/2017/08/24/azure-ad-delegation-scenario/">post</a> I talked about a delegation scenario with AzureAD and a classic Asp.Net web project. In this post I would like to explain a simpler solution: an Asp.Net Core 2.0 FrontEnd that needs to access a backend Api, both secured with the same AzureAD directory.

<a href="https://msdnshared.blob.core.windows.net/media/2017/10/simple-AAD.png"><img class="aligncenter size-full wp-image-265" alt="Basic AzureAD scenario" src="https://msdnshared.blob.core.windows.net/media/2017/10/simple-AAD.png" width="430" height="185" /></a>

Even if the theory and the protocols behind are always the same (OAuth2/OpenIdConnect) in Asp.Net Core 2.0 the default behavior is different, so we need to take and code different steps.

These are the major differences:
<ul>
 	<li>On client side we need to use <a href="https://www.nuget.org/packages/Microsoft.Identity.Client">MSAL</a> and not <b>ADAL</b> to obtain a token</li>
 	<li>On server side we need to configure the middleware to support AzureAd</li>
 	<li>The <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-dev-understanding-oauth2-implicit-grant"><b>implicit flow</b></a> is used (opposed to the "<strong>authorization code flow</strong>")</li>
</ul>
In order to protect with AAD an Asp.Net Core 2.0 project we need to add the <b>OpenIdConnect</b> support and configure it properly. This is not a trivial task, but fortunately, we can grab the needed code from the standard Asp.Net Core 2.0 template. If we create a new web project and select the "work or school account" authentication option we will have all the needed classes in the files <b>AzureAdAuthenticationBuilderExtensions </b>and<b> AzureAdOptions</b>. With these files enabling the authentication is straight forward, as we just need to configure the AzureAd parameters in the <b>appsettings.json</b> and the client secret using the "manage user secrets" option.

By default the authentication library uses the "<b>implicit flow</b>", that means the client (browser) will get the required tokens directly from the authentication server. So differently from the "<b>authorization code flow</b>" (used with ADAL in Asp.Net) the server side receives the tokens from the caller and there is no "authorization code" that need to be redeemed. In other words this means the server side has no way to exchange the user credentials for an access token for the Api layer.

Again by default the authentication library tells the client to ask only for the identity token (<b>id_token</b>) and not for any access token, so to obtain an access token for the Api layer we need to explicitly enable it:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #008000">//enable the access token request</span>
options.ResponseType = <span style="color: #a31515">"token id_token"</span>;
	     
<span style="color: #008000">//the target resource ID (access token for?)</span>
options.Resource = <span style="color: #a31515">"XXXXXX-YYYYYY-ZZZZZ-WWWWW"</span>;

<span style="color: #008000">//save tokens in the request context</span>
options.SaveTokens = <span style="color: #0000ff">true</span>;
	    
<span style="color: #008000">//these lines must be added in the Configure method of the ConfigureAzureOptions class.</span>
</pre>
</div>
It is important to note that kind of response type for the implicit flow is not enabled by default for AzureAd, so we need to edit the manifest via the Azure portal and enable it (for the FrontEnd application):

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #a31515">"oauth2AllowImplicitFlow"</span>: <span style="color: #0000ff">true</span>
</pre>
</div>
The library saves the tokens sent by the client in the HttpContext, so it is really easy retrieve them:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #2b91af">string</span> accessToken = <span style="color: #0000ff">await</span> HttpContext.GetTokenAsync(<span style="color: #a31515">"access_token"</span>);
<span style="color: #2b91af">string</span> idToken = <span style="color: #0000ff">await</span> HttpContext.GetTokenAsync(<span style="color: #a31515">"id_token"</span>);
</pre>
</div>
Remember that the <b>id_token</b> represents the user for the current resource and cannot be used to access other resources. Vice versa the <strong>access_token</strong> is meant only for the target resource specified in request the options, so we need to use the latter to call the Api layer:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%"><span style="color: #008000">//example of Autorest client, created with --add-credentials </span>
<span style="color: #2b91af">string</span> accessToken = <span style="color: #0000ff">await</span> HttpContext.GetTokenAsync(<span style="color: #a31515">"access_token"</span>);
<span style="color: #2b91af">var</span> credentials = <span style="color: #0000ff">new</span> TokenCredentials(accessToken);
IMyApiLayer apiClient = <span style="color: #0000ff">new</span> MyApiLayer(credentials);
apiClient.BaseUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #a31515">"https://localhost:57736"</span>);
<span style="color: #2b91af">var</span> obj = apiClient.MyMethod();
</pre>
</div>
You can find a sample demo code <a target="_blank" href="https://github.com/gianlucb/Demo_AAD.2tiers" rel="noopener">here</a>]]></content:encoded>
    </item>
    <item>
      <title>Create a Service Fabric Application on demand</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/create-a-service-fabric-application-on-demand</link>
      <pubDate>Tue, 26 Sep 2017 11:20:47 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=247</guid>
      <description><![CDATA["Hello World"!
You probably already know that the Service Fabric SDK allows a developer to fully...]]></description>
      <content:encoded><![CDATA["Hello World"!
You probably already know that the Service Fabric SDK allows a developer to fully manage the cluster, the nodes, and the deployed applications by code.

One of the features I like most of the Service Fabric programming is the ability to dynamically create and deploy new services. Or more in general the ability to manage the lifecycle of the running services.

For example, If we want to deploy a new instance of an Application we just need few lines of code:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">FabricClient fabricClient = <span style="color: #0000ff">new</span> FabricClient();
Uri eventDeploymentUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #a31515">"fabric:/NewApp/"</span>);           
          
<span style="color: #008000">//check for existence</span>
<span style="color: #0000ff">await</span> fabricClient.QueryManager.GetApplicationListAsync(eventDeploymentUri);
<span style="color: #0000ff">if</span> (applicationList.Count &gt; 0) <span style="color: #0000ff">return</span>; <span style="color: #008000">//already exists</span>

<span style="color: #008000">//passing manifest parameters to the new application</span>
NameValueCollection appParameters = <span style="color: #0000ff">new</span> NameValueCollection();
appParameters.Add(<span style="color: #a31515">"Param1"</span>,<span style="color: #a31515">"1"</span> );

ApplicationDescription applicationDesc = 
	<span style="color: #0000ff">new</span> ApplicationDescription(eventDeploymentUri, <span style="color: #a31515">"APP_TYPE"</span>, <span style="color: #a31515">"APP_VERSION"</span>, appParameters);
<span style="color: #0000ff">await</span> fabricClient.ApplicationManager.CreateApplicationAsync(applicationDesc);
</pre>
</div>
&nbsp;

This is super easy, we just ask the creation of a specific version of a registered application type (the type must be already registered).
The cluster will take care of this operation in an async way and will manage all the tasks related to this new deployment (like moving other services, leveling the volume load, register the name in reverse proxy ..etc..).

This dynamic operation is really useful if we want to build a multi-tenant or self-service solution that can instantiate multiple applications on-demand.
To demonstrate this, I created a sample demo <a href="https://github.com/gianlucb/Demo_SFOnDemandApplications">project</a> that builds websites on demand with just a simple REST api call.
In such demo the dynamically built application hosts an asp.net core website with a single page. The website is externally reachable as it is registered with the reverse proxy (read this <a href="https://blogs.msdn.microsoft.com/gianlucb/2017/09/11/service-fabric-reverse-proxy-port-discovery/">post</a> for more info about this point).

Hope you will find this demo solution helpful to start with service fabric SDK programming.]]></content:encoded>
    </item>
    <item>
      <title>Service Fabric Reverse Proxy Port discovery</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/service-fabric-reverse-proxy-port-discovery</link>
      <pubDate>Mon, 11 Sep 2017 17:50:12 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=246</guid>
      <description><![CDATA[Hello World!

The reverse proxy is a feature of Service Fabric that allows to expose internal...]]></description>
      <content:encoded><![CDATA[Hello World!

The reverse proxy is a feature of Service Fabric that allows to expose internal endpoints, taking care of naming resolution, discovery and maintenance. Basically each service can be reached using an URI like:
<p style="text-align: center"><a href="#">https://cluster-fqdn:PORT/[ApplicationName]/[ServiceName]</a></p>
In this Uri <b>PORT</b> is the Reverse Proxy port, <b>ApplicationName</b> is the name of the deployed application (root of many services) and <b>ServiceName</b> is the name of the single service inside the application package.

Unfortunately the reverse proxy port is not fixed! It depends from the node where the application is running, so it can even change during the application lifetime. This because the port is defined by the node type, so if the application change node type it changes the port.

To avoid this you can force an application to be deployment only on a specific node type:

<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">&lt;PlacementConstraints&gt;
 NodeType == NodeType2
&lt;/PlacementConstraints&gt;
</pre>
</div>
By the way even with a fixed node type, the port is not "well-known" and can change from cluster to cluster (as it is defined in the cluster config).

If you need to get the port by code at runtime unfortunately  there isn't an easy way yet. Basically you need to manually parse the xml cluster manifest, get the list of the node types, find the type where your application is deployed and then read the properties of the <b>HttpApplicationGatewayEndpoint </b>element.

You can check the code needed for this looking at this simple project: <a href="https://github.com/gianlucb/SFhelper">SFHelper</a>

Also published as nuget package : <a href="https://www.nuget.org/packages/SFHelper/">https://www.nuget.org/packages/SFHelper/</a>]]></content:encoded>
    </item>
    <item>
      <title>Experimenting with Azure Managed Applications</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/experimenting-with-azure-managed-applications</link>
      <pubDate>Fri, 25 Aug 2017 15:56:11 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=245</guid>
      <description><![CDATA["Hello World"!
Today I'm playing with the new service "Azure Managed Applications" (Service...]]></description>
      <content:encoded><![CDATA["Hello World"!
Today I'm playing with the new service "<a href="https://docs.microsoft.com/en-us/azure/azure-resource-manager/managed-application-overview">Azure Managed Applications</a>" (Service Catalog) and would like to write down some key points I learned, and can be hopefully useful for new comers:
<ul>
 	<li>when you create a managed application this is nothing else than a standard ARM template, you need to create also other two JSON files but these are just for UI and some related stuff.</li>
 	<li>The ARM template will be deployed in the end-user subscription, but we get the access to the resources!</li>
 	<li>The end-user will not get access to the resources created, so we can "safely" deploy our intellectual properties</li>
 	<li>Being just an ARM template this defines a set of resources and their interconnections, by default so does not deploy any Bits or piece of code.</li>
 	<li>Once the end-user has created the managed application we can deploy our solution, having access to the created group</li>
</ul>
But If we want to have a "ready-to-use"/"self-installing", application we need to use an ARM template that deploys the solution code after the resources creation, otherwise the experience for the end-user will be an "empty" set of resources, and he needs to wait for us to deploy the solution in its group.

Some template resources can execute extra steps after the resource creation, for example:
<ul>
 	<li>You can execute custom <a href="https://docs.microsoft.com/en-us/azure/virtual-machines/windows/extensions-customscript">scripts</a> on VM</li>
 	<li>A Web app can use WebDeploy to automatically deploy the code:</li>
</ul>
<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">{
    "name": <span style="color: #a31515">"MSDeploy"</span>,
    "type": <span style="color: #a31515">"extensions"</span>,
    "location": <span style="color: #a31515">"[resourceGroup().location]"</span>,
    "apiVersion": <span style="color: #a31515">"2015-08-01"</span>,
    "dependsOn": [
        <span style="color: #a31515">"[resourceId('Microsoft.Web/sites', parameters('webAppName'))]"</span>
    ],
    "tags": {
        "displayName": <span style="color: #a31515">"WebDeployMyProfile"</span>
    },
    "properties": {
        "packageUri": <span style="color: #a31515">"https://dx.blob.core.windows.net/dx-stageartifacts/content/MyDeploy.zip?st=2....-08-21T08%3A13%3A00Z&amp;sp=rl&amp;sv=2016-05-22&amp;sr=b&amp;sig=DfI556J0yG09pvw2Pkuliuhj7gxODmJb0p04Rq60oqc8%3D"</span>,
        "dbType": <span style="color: #a31515">"None"</span>,
        "connectionString": <span style="color: #a31515">""</span>,
        "setParameters": {
	    "IIS Web Application Name": <span style="color: #a31515">"[parameters('webAppName')]"</span>
	    }
	}
}
</pre>
</div>
&nbsp;

Note: This is still in preview, so things may change very quickly :-)]]></content:encoded>
    </item>
    <item>
      <title>Azure AD Delegation scenario</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/azure-ad-delegation-scenario</link>
      <pubDate>Thu, 24 Aug 2017 10:03:54 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=175</guid>
      <description><![CDATA[tl;dr

 	Register a new Web App in AAD for the Api

 	Add the required "delegated" permissions...]]></description>
      <content:encoded><![CDATA[<b>tl;dr</b>
<ol>
 	<li>Register a new Web App in AAD for the Api
<ol type="a">
 	<li>Add the required "delegated" permissions to the external resource (i.e: Microsoft Graph)</li>
</ol>
</li>
 	<li>Register a new Web App in AAD for the FrontEnd
<ol type="a">
 	<li>Add the permissions to access the Api app</li>
</ol>
</li>
 	<li>Configure the Web apps code with the authentication details as usual (ClientID, Client Secret, Audience Uri..etc..). <strong>ADAL</strong> is the right choice for .NET code</li>
 	<li>In Azure portal edit the Api registration manifest adding the GUID of the FronEnd app:<em>
"<b>knownClientApplications</b>": ["XXXXXX-YYYY-ZZZZZZ-WWWWW-XXXXXXX"]</em></li>
 	<li>In the Api app code, save the bootstrap token during logon and use it to ask a new "<b>On-Behalf-Of</b>" token for the external resource with the user assertion "<b>urn:ietf:params:oauth:grant-type:jwt-bearer</b>"</li>
</ol>
"Hello World"!
Protect a web resource with Azure AD is really easy and well <a href="https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect/">documented</a>, but in a delegation scenario where we need to access to an external resource impersonating the signed-in user the things can get little more complicated.
<span>Is not difficult, we just need few extra steps and configuration from the base</span><span> case. </span>

If I would like to implement an architecture as the following:

&nbsp;

<a href="https://msdnshared.blob.core.windows.net/media/2017/08/delegation-AAD.png"><img width="660" height="208" class="aligncenter size-full wp-image-235" alt="" src="https://msdnshared.blob.core.windows.net/media/2017/08/delegation-AAD.png" /></a>The very first steps are:
<ol>
 	<li>Register a new Web App in AAD for the Api
<ol type="a">
 	<li><span>Add a redirect URL with "</span><a href="https://localhost">https://localhost</a><span>"</span></li>
 	<li>Add the required "delegated" permissions to the external resource (i.e: Microsoft Graph)</li>
</ol>
</li>
 	<li>Register a new Web App in AAD for the Frontend
<ol type="a">
 	<li><span>Add redirect URLs to point to the main page</span></li>
 	<li>Add the permissions to access the Api app</li>
</ol>
</li>
 	<li>Configure the apps code with the authentication details as usual (ClientID, Client Secret, Audience Uri..etc..)</li>
</ol>
<span>As you know the first time we access a resource protected by an <strong>Oauth</strong> based protocol (like <strong>OpenIDConnect</strong> in AAD) we need to "visually" grant the access to that resource. The classic HTML page that requires the user input to continue. </span><span>Because at step 2/b we specified the FrontEnd app needs to access the Api app the user will be prompted to confirm the access to both applications (</span><span>FrontEnd + Api) in a single page.</span>

By default the <strong>ADAL</strong> library uses the <strong>OpenIDConnect</strong> "<strong>authorization code flow</strong>". This means that the FrontEnd app receives an authorization code as part of the login process. This authorization code can be reedemed and exchanged for an <strong>access token</strong> for the Api app. With ADAL this task can be done in the <em>AuthorizationCodeReceived</em> notification event (in <em>Startup.Auth.cs</em>).

So far so good. We have authenticated the user, received an <strong>id_token</strong> that identifies the caller, reedemed the authorization code and obtained the <strong>access_token</strong> for the Api layer. Thus we can access the Api app as the calling user.

Unfortunately this is not sufficent if the Api app needs to access an external resource acting as the signed in user (third hop). This because the token received from this layer is meant only to the Api app and cannot be used to access the external resource (i.e: Microsoft Graph). We need a specific token for this latter resource but there are two major issues at this point:
<ol>
 	<li>The user didn't be prompted for that, so he never granted the access to the external resource</li>
 	<li>The Api app is called via code (REST API) and therefore cannot display any HTML page to ask for such grant</li>
</ol>
In any case we also would like to silently access this resource in a SSO manner without asking again for credentials. Basically we need a way to grant the access to the external resource via the Api layer upfront. Fortunately this is possible manually editing the registration manifest for the Api app in the Azure portal:

<!-- HTML generated using hilite.me --><div style="background: #ffffff;overflow:auto;width:auto;border:solid gray;border-width:0em;padding:.2em .6em"><pre style="margin: 0;line-height: 125%"><span style="color: #a31515">&quot;knownClientApplications&quot;</span>: [<span style="color: #a31515">&quot;XXXXXX-YYYY-ZZZZZZ-WWWWW-XXXXXXX&quot;</span>]
</pre></div>


Adding the GUID of the FrontEnd app to the "<strong>knownClientApplications</strong>" property we link the two registrations. This means the first time the user access the FrontEnd app, he will be prompted to grant the access for all the permissions specified by both apps and not only by the FrontEnd one. In other words, we obtain a consensus page that lists all the permissions and all the external resources accessed by the current application and all the linked ones.

Now, as the user grants the access to all the resources upfront, the Api app can request a token for the external resource in a SSO manner. In this case we need to use the "<b>On-Behalf-Of flow</b>" that allows to get an access token that delegates the user credentials. To successfully request this kind token we need to:
<ul>
 	<li>provide the <b>Bootstrap</b> Token (this is just terminology, is the <strong>access_token</strong> sent by the FrontEnd to the Api app)</li>
 	<li>Specify the assertion "<b>urn:ietf:params:oauth:grant-type:jwt-bearer</b>"</li>
</ul>
if you are using <strong>ADAL</strong> this translates in two simple steps:
<ul>
 	<li><strong>SaveSigninToken</strong> = <strong>true</strong> in <em>TokenValidationParameters</em> (as by default for performance is discarded after the access)</li>
 	<li>Request the token with:</li>
</ul>
<!-- HTML generated using hilite.me -->
<div style="background: #ffffff;overflow: auto;width: auto;border: solid gray;border-width: 0em;padding: .2em .6em">
<pre style="margin: 0;line-height: 125%">UserAssertion userAssertion = <span style="color: #0000ff">new</span> UserAssertion(bootstrapContext, <span style="color: #a31515">"urn:ietf:params:oauth:grant-type:jwt-bearer"</span>, userName);
<span style="color: #2b91af">var</span> result = <span style="color: #0000ff">await</span> authContext.AcquireTokenAsync(resourceUri, clientCred, userAssertion);</pre>
</div>
&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>WCF ETW Tracing</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/wcf-etw-tracing</link>
      <pubDate>Fri, 28 Oct 2016 16:10:11 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=165</guid>
      <description><![CDATA["Hello World"!

Today I would like to share a quick way to enable and collect WCF tracing, machine...]]></description>
      <content:encoded><![CDATA["Hello World"!

Today I would like to share a quick way to enable and collect WCF tracing, machine wide, without any configuration change!

We are all used to enable WCF diagnostic tracing using the application/web configuration file (leveraging our friend <em>System.Diagnostics.XmlWriterTraceListener</em>). But WCF uses also ETW for tracing, so we have a second option! The ETW provider used is called "<em>Microsoft-Windows-Application Server-Applications</em>".
You can easily enable the tracing and convert the result to an human-readable text file with:
<ul>
 	<li><strong>logman start WCFETWTracing -p "Microsoft-Windows-Application Server-Applications" -nb 256 1024 -bs 512 -ets -ct perf -f bincirc -max 500 -o mywcftrace.etl</strong></li>
 	<li>…execute the program…</li>
 	<li><strong>logman.exe stop WCFETWTracing –ets</strong></li>
 	<li><strong>netsh trace convert input=mywcftrace.etl wcf_repro.txt TXT</strong></li>
</ul>
If you prefer to use powershell check the following <a href="https://github.com/gianlucb/WCF-ServiceSelfhost/blob/master/EnableETW-WCFTracing.ps1">script</a>

Please note that this ETW tracing is machine wide! If you want to collect the data only for one process you may use other methods/tools like <a href="https://www.microsoft.com/en-us/download/details.aspx?id=28567">Perfview</a>.

Last but not least, this tracing can also be enabled through the event viewer: <strong>Application Server-Applications / Debug </strong>and<span><strong> Analytic</strong> </span>logs]]></content:encoded>
    </item>
    <item>
      <title>WIF 4.5  Active/Passive/Delegation examples</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/wif-4-5-activepassivedelegation-examples</link>
      <pubDate>Wed, 05 Oct 2016 12:55:09 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=156</guid>
      <description><![CDATA["Hello World"!

Lately more and more customers are asking me help and examples on how to use WIF...]]></description>
      <content:encoded><![CDATA["Hello World"!

Lately more and more customers are asking me help and examples on how to use WIF 4.5+WCF in their projects, just a quick jump-start or how to "migrate" from the previous version (WIF on .NET 3.5).

As you may know WIF is now part of the framework so the first thing to note is the change of namespace: from <b>Microsoft.IdentityModel</b> to <b> System.IdentityModel</b>. Second some classes are gone and some has been renamed.

<span>I created two working examples on how to use WIF 4.5 to secure a WCF web service. </span><span> I tried to mock up the two most common scenarios:</span>
<ul>
 	<li><b>#1 standard active scenario (1 hop / Client -&gt; WCF)</b>
<a href="https://github.com/gianlucb/WIF-ActiveScenarioWCF"><span>https://github.com/gianlucb/WIF-ActiveScenarioWCF</span></a></li>
 	<li><b>#2 delegation scenario (2 hops / Browser -&gt; WEB -&gt; WCF )</b>
<a href="https://github.com/gianlucb/WIF-DelegationScenarioWCF"><span>https://github.com/gianlucb/WIF-DelegationScenarioWCF</span></a></li>
</ul>
Basically WIF is used to secure a target WCF resource (<b>Relying party</b>) and also to retrieve the access token from the <b>STS</b>. I used an ADFS server but you can use any custom STS implementation.

I put many comments in the source code and tried to be verbose as much as possible in order to help you to understand how WIF works and how must be configured.
In these examples you can find also how to configure WIF programmatically, without using any configuration file!

The example #1 is really simple, just a WCF service that must be consumed using a SAML Token as authentication method.
Active scenario simply means the caller must go to STS to retrieve the token before to call the service, is not redirected automatically as happens with a browser for example.

<span>The example #2 is the implementation of this "old" guide: </span><a href="https://technet.microsoft.com/en-us/library/adfs2-identity-delegation-step-by-step-guide(v=ws.10).aspx"><span>Identity Delegation with AD FS 2.0 Step-by-Step Guide</span></a><span>. The guide was about .NET 3.5, the old VS version and ADFS 2.0, so it not updated anymore. </span>
Nowadays to setup a working delegation scenario there are some additional steps and some that are not necessary anymore, see the readme document for a detailed list of required steps for a delegation.
Note that for a delegation scenario the service's caller must get a second token of type <b>OnBehalfOf</b> or <b>ActAs</b>, it cannot use the user's original token.
In this example you can find two methods for this task:
<ul>
 	<li>Automatic: using <b>CreateChannelWithOnBehalfOfToken</b> (WCF get the token for us transparently)</li>
 	<li>Manual: call STS with <b>WSTrustChannelFactory</b> and forward the token with <b>CreateChannelWithIssuedToken </b></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Windows 10 App insights with Cortana</title>
      <link>https://docs.microsoft.com/archive/blogs/gianlucb/windows-10-app-insights-with-cortana</link>
      <pubDate>Wed, 11 May 2016 16:11:35 GMT</pubDate>
      <dc:creator><![CDATA[GianlucaBertelli]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/gianlucb/?p=115</guid>
      <description><![CDATA["Hello World"!

My need was to quickly visualize a report of one of my published apps in the...]]></description>
      <content:encoded><![CDATA["Hello World"!

My need was to quickly visualize a report of one of my published apps in the Windows Store. I just wanted a quick way to see the rating, the number of reviews and the active users. These information were all already available but scattered over many websites: mobile engagement, hockey app and windows store analytics to name a few. So I decided to bring all the data together and summarize them in a single view. What better of Cortana to visualize the report?

<a href="https://msdnshared.blob.core.windows.net/media/2016/05/cortana.png"><img class=" wp-image-116 aligncenter" src="https://msdnshared.blob.core.windows.net/media/2016/05/cortana.png" alt="Cortana and Windows Store app insights" width="243" height="424" /></a>

In order to achieve this I created a really simple solution composed by:
<ul>
	<li>Asp.Net REST web service (hosted on Azure as API app)</li>
	<li>PowerBi dashboard</li>
</ul>
The web service has the responsibility to extract the data from all the sources and to expose the data as lists of items (JSON). In my case for sake of simplicity I choose to track active users with a custom monitoring implementation (an alternative is to <a href="https://azure.microsoft.com/en-us/documentation/articles/mobile-engagement-api-export-overview/">export</a> the data from Mobile Engagement API). This service is also able to pull all the app reviews from the windows store as detailed in my <a href="https://blogs.msdn.microsoft.com/gianlucb/2016/03/04/how-to-programmatically-get-app-reviews-from-windows-store/">previous blog post</a> .

PowerBi is obviously the main part in this solution, it allowed me to quickly import the data from my web service and quickly transform the lists in fancy charts. The <a href="https://powerbi.microsoft.com/en-us/blog/announcing-power-bi-integration-with-cortana-and-new-ways-to-quickly-find-insights-in-your-data/">Cortana integration</a> is provided by PowerBi and is really simple to setup:
<ul>
	<li>Import all your sources (i.e: the web service URL)</li>
	<li>Create a new report and configure it to work with Cortana:
<ul>
	<li>set the page size to "<strong>Cortana</strong>"</li>
	<li>set the <b>keywords</b> to use</li>
</ul>
</li>
</ul>
<a href="https://msdnshared.blob.core.windows.net/media/2016/05/powerbi.png"><img class="aligncenter wp-image-136" src="https://msdnshared.blob.core.windows.net/media/2016/05/powerbi.png" alt="PowerBi Cortana Settings" width="130" height="181" /></a>
<ul>
	<li>Create the visualizations (charts)</li>
	<li>If working with PowerBi Desktop client then publish the report to PowerBi online</li>
</ul>
Last point is to enable the Cortana integration and the scheduled refresh for each dataset:
<ul>
	<li>Go to <a href="https://www.powerbi.com/">powerbi.com</a></li>
	<li>Go to settings page, Datasets -&gt; Your Dataset
<ul>
	<li>Enable the <b>Scheduled Refresh </b></li>
	<li><b>Q&amp;A and Cortana -&gt; Allow Cortana to access this dataset</b></li>
</ul>
</li>
</ul>
After the publish it took a while before to be ready for Cortana but once done was really straightforward to use. To get the report I just need to write one of the specified <b>keywords</b> in Cortana and wait until a match is found (actually when the PowerBi icon is shown):

<a href="https://msdnshared.blob.core.windows.net/media/2016/05/keywords.png"><img class="aligncenter wp-image-126" src="https://msdnshared.blob.core.windows.net/media/2016/05/keywords.png" alt="Cortana found PowerBy report" width="300" height="86" /></a>

This report is available only on the devices where I synchronized the PowerBi account.

Of course this is a really simple solution, just a proof of concept (PoC) of what a real solution can be. In case of an huge set of data I would also introduce some additional caching layers to store and organize the data in a more consistent way.

Note that I created a middle tier web service that aggregates the data from multiple sources only because some of them were not "PowerBi ready" ! In a more simple way you can achieve a very similar solution without the need of a intermediate web service but just importing the <a href="https://powerbi.microsoft.com/en-us/documentation/powerbi-content-pack-windows-dev-center/">Windows Dev Center content pack</a> in PowerBi.]]></content:encoded>
    </item>
  </channel>
</rss>