Skip to content

Instantly share code, notes, and snippets.

@robertmuehsig
Created October 8, 2018 09:10
Show Gist options
  • Save robertmuehsig/d3439f60cb5540b6c442f21d5a464f62 to your computer and use it in GitHub Desktop.
Save robertmuehsig/d3439f60cb5540b6c442f21d5a464f62 to your computer and use it in GitHub Desktop.
services.AddAuthentication()
.AddOpenIdConnect(office365Config.Id, office365Config.Caption, options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.ClientId = office365Config.MicrosoftAppClient;
options.ClientSecret = office365Config.MicrosoftAppClientSecret;
options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };
options.Authority = office365Config.AuthorizationEndpoint;
options.SignedOutRedirectUri = office365Config.Url;
options.ResponseType = "code id_token";
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
options.CallbackPath = "/oidc-signin";
foreach (var scope in office365Scopes)
{
options.Scope.Add(scope);
}
options.Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async context =>
{
var clientCred = new ClientCredential(office365Config.MicrosoftAppClient, office365Config.MicrosoftAppClientSecret);
var authContext = new AuthenticationContext(office365Config.AuthorizationEndpoint);
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code.ToString(), new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred);
try
{
var graphServiceClient = new GraphServiceClient(new AccessTokenAuthenticationProvider(authResult.AccessToken));
var groupies = await graphServiceClient.Me.GetMemberGroups(false).Request().PostAsync();
// ...
}
catch (Exception exc)
{
// ...
}
}
};
});
@robertmuehsig
Copy link
Author

robertmuehsig commented Oct 8, 2018

The AccessTokenAuthProvider:


public class AccessTokenAuthenticationProvider : Microsoft.Graph.IAuthenticationProvider
{
    private readonly string _existingAccessToken;

    public AccessTokenAuthenticationProvider(string existingAccessToken)
    {
        _existingAccessToken = existingAccessToken;
    }

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("bearer", _existingAccessToken);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment