Buscar contenidos

jueves, 31 de enero de 2019

Integración de una aplicación NetCore/MVC con Azure Active Directory


Cambiar en el Manifiesto de la aplicación

Como habilitar Claim
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims


Claim opcional disponibles
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-claims-mapping




  public void ConfigureServices(IServiceCollection services)
        {     
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<IPrincipal>(
                provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

...



Vistas para hacer SignOut y SignIn:


Appsetting.ambiente.json

{
    "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",     
        "Domain": "dev2tenant.onmicrosoft.com",
        "TenantId": "254e256b-76d7-4ada-8bb6-74de17393e91",
        "ClientId": "bbd174db-474b-4750-bd0d-a67c01369c13",
        "CallbackPath": "/signin-oidc"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    }
}



martes, 29 de enero de 2019

Adding Swagger to ASP.NET Core Web API using XML Documentation


https://exceptionnotfound.net/adding-swagger-to-asp-net-core-web-api-using-xml-documentation/


The Package

First, we need to grab the NuGet package for the project known as Swashbuckle.AspNetCore. This package adds Swagger, SwaggerUI, and other libraries to make it easy for us to create our API documentation.
With the package installed, we now need to enable our project to generate XML comments. The comments come from triple-slash (///) comments throughout our code.
First, in the project properties, check the box labeled "Generate XML Documentation".
Screenshot of the Project Properties page, with the Generate XML Documentation checkbox highlighted
You will probably also want to suppress warning 1591, which will now give warnings about any method, class, or field that doesn't have triple-slash comments.
Screenshot of the Project Properties page, with the Suppress Warnings box highlightes and warning 1591 added

Configuring Swagger

With the project now generating XML documentation, we need to make some changes to our Startup.cs file. Specifically, we need to enable the services layer to use Swagger and tell the app to use both Swagger and Swagger UI. Here's the code; details are immediately after.
public class Startup
{
    //...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //This line adds Swagger generation services to our container.
        services.AddSwaggerGen(c =>
        {
            //The generated Swagger JSON file will have these properties.
            c.SwaggerDoc("v1", new Info
            {
                Title = "Swagger XML Api Demo",
                Version = "v1",
            });
            
            //Locate the XML file being generated by ASP.NET...
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            
            //... and tell Swagger to use those XML comments.
            c.IncludeXmlComments(xmlPath);
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        //This line enables the app to use Swagger, with the configuration in the ConfigureServices method.
        app.UseSwagger();
        
        //This line enables Swagger UI, which provides us with a nice, simple UI with which we can view our API calls.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML Api Demo v1");
        });
    }
}

Ejemplo Subir archivos Sync/Async c#/MVC




Ver Código 

Discusión:

https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean


Analisis

1. (fuente)
Synchronous is not ideal for multiple, large CSV file since you will need to wait until the file is processed by the server to submit another request. On large files, this also may cause your browsers to return with timeout errors due to the server being too busy. If you have multiple files, asynchronous will allow you to submit multiple files to the server queue to be processed with a email receipt once completed.


2. (fuente)
But, like all things in programming, it’s not something that you should use in every instance; in fact, there are some situations in which you should avoid it. Asynchronous programming has actually been around for a long time, but in recent years, it’s become more widely used. According to Mike James at iProgrammer, “Often the programmer is fully aware that what they are doing is object oriented but only vaguely aware that they are writing asynchronous code.” So, we set out to identify the best use cases for async as well as situations in which you shouldn’t use it. We searched the web for insights and reached out to a panel of programmers and asked them to answer this question:

miércoles, 23 de enero de 2019

Azure AD B2C - Role management


https://stackoverflow.com/questions/45885795/azure-ad-b2c-role-management/45903151

Azure AD B2C does not yet include Group claims in the token it sends to the application thus you can't follow the same approach as you outlined with Azure AD (which does include group claims in the token).
You can support this feature ask by voting for it in the Azure AD B2C feedback forum: Get user membership groups in the claims with Azure AD B2C
That being said, you can do some extra work in this application to have it manually retrieve these claims the group claims and inject them into the token.
First, register a separate application that'll call the Microsoft Graph to retrieve the group claims.
  1. Go to https://apps.dev.microsoft.com
  2. Create an app with Application Permissions : Directory.Read.All.
  3. Add an application secret by clicking on Generate new password
  4. Add a Platform and select Web and give it any redirect URI, (e.g. https://yourtenant.onmicrosoft.com/groups)
  5. Consent to this application by navigating to: https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI
Then, you'll need to add code the following code inside of the OnAuthorizationCodeReceivedhandlerright after redeeming the code:
var authority = $"https://login.microsoftonline.com/{Tenant}";
var graphCca = new ConfidentialClientApplication(GraphClientId, authority, GraphRedirectUri, new ClientCredential(GraphClientSecret), userTokenCache, null);
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

try
{
    AuthenticationResult authenticationResult = await graphCca.AcquireTokenForClientAsync(scopes);
    string token = authenticationResult.AccessToken;

    using (var client = new HttpClient())
    {
        string requestUrl = $"https://graph.microsoft.com/v1.0/users/{signedInUserID}/memberOf?$select=displayName";

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

        HttpResponseMessage response = await client.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();

        var json = JObject.Parse(responseString);

        foreach (var group in json["value"])
            notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, group["displayName"].ToString(), System.Security.Claims.ClaimValueTypes.String, "Graph"));

        //TODO: Handle paging. 
        // https://developer.microsoft.com/en-us/graph/docs/concepts/paging
        // If the user is a member of more than 100 groups, 
        // you'll need to retrieve the next page of results.
    }
} catch (Exception ex)
{
    //TODO: Handle
    throw;
}