GithubHelp home page GithubHelp logo

isabella232 / microsoft-authentication-graph-helpers Goto Github PK

View Code? Open in Web Editor NEW

This project forked from thenetworg/microsoft-authentication-graph-helpers

0.0 0.0 0.0 18 KB

Library which showcases easier manipulation with Microsoft Graph and ADAL for your ASP.NET application.

Home Page: https://github.com/AzureAD/microsoft-identity-web

C# 100.00%

microsoft-authentication-graph-helpers's Introduction

Microsoft Graph Helpers

Follow: https://github.com/AzureAD/microsoft-identity-web for better and supported approach based on MSAL.

The purpose of this library is to simplify the interaction with Microsoft's authentication libraries and calling 1st party and other APIs.

Please keep on mind that this is still work in progress and there are things like Data Protection into the cache etc. missing right now.

Setup

  1. Add to Dependency Injection
    // This library depends on MemoryCache / DistributedMemorycache for storing Tokens from the TokenCache
    services.AddMemoryCache();
    
    services.AddSingleton(new ClientCredential(_config["AzureAd:ClientId"], _config["AzureAd:ClientSecret"]));
    services.AddScoped<TokenCacheFactory>();
    services.AddScoped<AdalFactory>();
    services.AddScoped<MicrosoftGraphFactory>();
    services.AddScoped<AzureAdGraphFactory>();
  2. Configure your OpenID Connect Middleware to redeem the code for token and store it into the cache
    services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
    {
        options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
        options.Events = new OpenIdConnectEvents()
        {
            OnAuthorizationCodeReceived = async context =>
            {
                var authContext = context.HttpContext.RequestServices.GetRequiredService<AdalFactory>().GetAuthenticationContextForUser(context.Principal);
                var clientCred = context.HttpContext.RequestServices.GetRequiredService<Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential>();
                var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, "https://graph.microsoft.com");
                context.HandleCodeRedemption(authResult.AccessToken, authResult.IdToken);
            },
        };
    });
  3. Profit
    public class HomeController : Controller
    {
        private readonly MicrosoftGraphFactory _graphFactory;
        public HomeController(MicrosoftGraphFactory graphFactory)
        {
            _graphFactory = graphFactory;
        }
        [Authorize]
        public async Task<IActionResult> Index()
        {
            var graphClient = _graphFactory.GetClientForUser(HttpContext.User);
            var users = await graphClient.Users.Request().GetAsync();
    
            return Json(users);
        }
        public async Task<IActionResult> IndexAsApp()
        {
            var tenantId = "";
            
            var graphClient = _graphFactory.GetClientForApplication(tenantId);
            var users = await graphClient.Users.Request().GetAsync();
    
            return Json(users);
        }
    }

Authorization Attribute

Once you have set up the above, you may also make use of the AzureAdAuthorizationAttribute. The purpose of this is to make authorization with Azure AD roles and groups more simple.

Thanks to this extension, you can make use of real-time group and role based authorization. Currently, the setup is that either of the requirements has to be met. If you want multiple, like group membership and role, just stack it on top of each other.

For this to work, you also need to add IHttpContextAccessor to your services.

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHttpContextAccessor();
    ...
}
public class HomeController : Controller
{
    [AzureAdAuthorization(roles: new string[] { AzureAdRoles.CompanyAdministrator }, groups: new string[] { ApplicationGroupIds.AppAdministrators })]
    public async Task<IActionResult> Index()
    {
        var graphClient = _graphFactory.GetClientForUser(HttpContext.User);
        var users = await graphClient.Users.Request().GetAsync();

        return Json(users);
    }
}

Using with APIs

In order for this to work, you need to have JwtBearerMiddleware setup correctly (with SaveTokens = true) for Azure AD in your project. This method simplifies the on-behalf-of flow token redemption while leveraging the token cache and everything.

public class HomeController : Controller
{
    private readonly MicrosoftGraphFactory _graphFactory;
    public HomeController(MicrosoftGraphFactory graphFactory)
    {
        _graphFactory = graphFactory;
    }
    [Authorize(JwtBearerDefaults.AuthenticationScheme)]
    public async Task<IActionResult> Index()
    {
        var graphClient = _graphFactory.GetClientForApiUser(HttpContext.GetTokenAsync("access_token"), HttpContext.User);
        var users = await graphClient.Users.Request().GetAsync();

        return Json(users);
    }
}

microsoft-authentication-graph-helpers's People

Contributors

hajekj avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.