I'm trying to create a DI for the following code from the Startup.cs file. But being new to .net I'm having a tough time figuring out a solution.
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>() as ITokenAcquisition;
var graphClient = GraphServiceClientFactory
.GetAuthenticatedGraphClient(async () =>
{
return await tokenAcquisition
.GetAccessTokenForUserAsync(GraphConstants.Scopes);
}
);
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using Microsoft.Identity.Web.UI;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Graph;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AD_Lookup
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages().AddRazorRuntimeCompilation();
// Add Microsoft Identity Platform sign-in
services.AddSignIn(options =>
{
Configuration.Bind("AzureAd", options);
options.Prompt = "select_account";
var authCodeHandler = options.Events.OnAuthorizationCodeReceived;
options.Events.OnAuthorizationCodeReceived = async context => {
// Invoke the original handler first
// This allows the Microsoft.Identity.Web library to
// add the user to its token cache
await authCodeHandler(context);
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>() as ITokenAcquisition;
var graphClient = GraphServiceClientFactory
.GetAuthenticatedGraphClient(async () =>
{
return await tokenAcquisition
.GetAccessTokenForUserAsync(GraphConstants.Scopes);
}
);
// Get user information from Graph
var user = await graphClient.Users["carvalhostephen20@hotmail.com"]
.Request()
.GetAsync();
context.Principal.AddUserGraphInfo(user);
};
options.Events.OnAuthenticationFailed = context => {
var error = WebUtility.UrlEncode(context.Exception.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
context.HandleResponse();
return Task.FromResult(0);
};
options.Events.OnRemoteFailure = context => {
if (context.Failure is OpenIdConnectProtocolException)
{
var error = WebUtility.UrlEncode(context.Failure.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
context.HandleResponse();
}
return Task.FromResult(0);
};
}, options =>
{
Configuration.Bind("AzureAd", options);
});
// Add ability to call web API (Graph)
// and get access tokens
services.AddWebAppCallsProtectedWebApi(Configuration,
GraphConstants.Scopes)
// Use in-memory token cache
// See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
.AddInMemoryTokenCaches();
// Require authentication
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
// Add the Microsoft Identity UI pages for signin/out
.AddMicrosoftIdentityUI();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//else
//{
// app.UseExceptionHandler("/Home/Error");
// // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// app.UseHsts();
//}
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Homecontroller.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using AD_Lookup.Models;
using Microsoft.Graph;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using Microsoft.Identity.Web.UI;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AD_Lookup.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private ITokenAcquisition _tokenAcquisition;
public HomeController(ILogger<HomeController> logger, ITokenAcquisition tokenAcquisition)
{
_logger = logger;
_tokenAcquisition = tokenAcquisition;
}
public IActionResult Index()
{
return View();
}
public IActionResult UserSearch()
{
//string searchText = model.SearchBoxText;
//ViewData["searchData"] = searchText;
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> SearchBox(UserSearchModel model)
{
string searchText = model.SearchBoxText;
ViewData["searchData"] = searchText;
var tokenAcquisition = this.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>() as ITokenAcquisition;
var graphClient = GraphServiceClientFactory
.GetAuthenticatedGraphClient(async () =>
{
var accessToken =
await tokenAcquisition.GetAccessTokenForUserAsync(GraphConstants.Scopes, "2b51e32f-e865-48ef-b075-0a456dc76468");
return accessToken;
// .GetAccessTokenForUserAsync(GraphConstants.Scopes, "2b51e32f-e865-48ef-b075-0a456dc76468");
}
);
var user = await graphClient.Users[searchText]
.Request()
.GetAsync();
return View();
//return Content($"Hello {model.SearchBoxText}");
}
public IActionResult GroupSearch()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Instead of copying the same code within my controller, I want to pass the values of tokenacquisition using DI.
Using the graph API I'm trying to print user information based on the email id inputted in a text box. The graphAPI provides the following code snippet that im trying to implement.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var user = await graphClient.Users["carvalhostephen20@hotmail.com"]
.Request()
.GetAsync();
This can be found at https://developer.microsoft.com/en-us/graph/graph-explorer Search for the sample query users by email. This is the functionality that i'm trying to implement.
Having the Startup.cs code copied into the controller causes solution to fail and return the following error page:

