Skip to content
This repository has been archived by the owner on Jun 17, 2024. It is now read-only.

added support for b2c #36

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions AuthBot.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AuthBot", "AuthBot\AuthBot.csproj", "{B8AD59D3-C36D-4E18-B504-06871001BC8D}"
EndProject
Expand All @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OneDriveBot", "OneDriveBot\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleAADv1Bot", "SampleAADv1Bot\SampleAADv1Bot.csproj", "{D2253234-1279-486E-8A63-D8C3424E0525}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleB2CBot", "SampleB2CBot\SampleB2CBot.csproj", "{D1B2B925-D8E2-44F9-A8A1-D07B789AFB34}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -33,8 +35,15 @@ Global
{D2253234-1279-486E-8A63-D8C3424E0525}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2253234-1279-486E-8A63-D8C3424E0525}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2253234-1279-486E-8A63-D8C3424E0525}.Release|Any CPU.Build.0 = Release|Any CPU
{D1B2B925-D8E2-44F9-A8A1-D07B789AFB34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1B2B925-D8E2-44F9-A8A1-D07B789AFB34}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1B2B925-D8E2-44F9-A8A1-D07B789AFB34}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1B2B925-D8E2-44F9-A8A1-D07B789AFB34}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9607E4D9-B5D4-4868-96E0-864AD81E3EE0}
EndGlobalSection
EndGlobal
7 changes: 6 additions & 1 deletion AuthBot/ContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ public static async Task<string> GetAccessToken(this IBotContext context, string
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
throw new NotImplementedException();
InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);
var result = await AzureActiveDirectoryHelper.GetB2CToken(authResult.UserUniqueId, tokenCache, scopes);
authResult.AccessToken = result.AccessToken;
authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
authResult.TokenCache = tokenCache.Serialize();
context.StoreAuthResult(authResult);
}
}
catch (Exception ex)
Expand Down
9 changes: 7 additions & 2 deletions AuthBot/Controllers/OAuthCallbackController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ public async Task<HttpResponseMessage> OAuthCallback()
[HttpGet]
[Route("api/OAuthCallback")]
public async Task<HttpResponseMessage> OAuthCallback(
[FromUri] string code,
[FromUri] string state,

[FromUri] string state,
[FromUri] string code,
CancellationToken cancellationToken)
{
try
Expand All @@ -63,6 +64,7 @@ public async Task<HttpResponseMessage> OAuthCallback(
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
tokenCache = new Microsoft.Identity.Client.TokenCache();
}

var resumptionCookie = UrlToken.Decode<ResumptionCookie>(queryParams);
Expand All @@ -87,6 +89,8 @@ public async Task<HttpResponseMessage> OAuthCallback(
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
var token = await AzureActiveDirectoryHelper.GetB2cTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache)tokenCache, Models.AuthSettings.Scopes);
authResult = token;
}

IStateClient sc = scope.Resolve<IStateClient>();
Expand Down Expand Up @@ -138,6 +142,7 @@ public async Task<HttpResponseMessage> OAuthCallback(
}
}


private int GenerateRandomNumber()
{
int number = 0;
Expand Down
35 changes: 34 additions & 1 deletion AuthBot/Helpers/AzureActiveDirectoryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace AuthBot.Helpers
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Models;
using Microsoft.Identity.Client;

public static class AzureActiveDirectoryHelper
{
Expand Down Expand Up @@ -54,7 +55,23 @@ public static async Task<string> GetAuthUrlAsync(ResumptionCookie resumptionCook
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
return null;
InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL();
Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication("https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0",
AuthSettings.ClientId, redirectUri.ToString(),
new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret),
tokenCache);


var uri = "https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0/authorize?response_type=code&&response_mode=query" +
"&client_id=" + AuthSettings.ClientId +
"&p=" + AuthSettings.Policy +
"&redirect_uri=" + HttpUtility.UrlEncode(AuthSettings.RedirectUrl) +
"&scope=" + HttpUtility.UrlEncode("openid profile offline_access") +
"&state=" + extraParameters;



return uri.ToString();
}
return null;
}
Expand All @@ -76,6 +93,15 @@ public static async Task<AuthResult> GetTokenByAuthCodeAsync(string authorizatio
return authResult;
}

public static async Task<AuthResult> GetB2cTokenByAuthCodeAsync(string authorizationCode, Microsoft.Identity.Client.TokenCache tokenCache, string[] scopes)
{
Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication("https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0", AuthSettings.ClientId, AuthSettings.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache);
Uri redirectUri = new Uri(AuthSettings.RedirectUrl);
var result = await client.AcquireTokenByAuthorizationCodeAsync(scopes, authorizationCode,AuthSettings.Policy);
AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache);
return authResult;
}

public static async Task<AuthResult> GetToken(string userUniqueId, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache, string resourceId)
{
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant, tokenCache);
Expand All @@ -91,6 +117,13 @@ public static async Task<AuthResult> GetToken(string userUniqueId, Microsoft.Ide
AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache);
return authResult;
}
public static async Task<AuthResult> GetB2CToken(string userUniqueId, Microsoft.Identity.Client.TokenCache tokenCache, string[] scopes)
{
Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication("https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0",AuthSettings.ClientId, AuthSettings.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache);
var result = await client.AcquireTokenSilentAsync(scopes, userUniqueId, "https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0",AuthSettings.Policy,false);
AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache);
return authResult;
}

public static string TokenEncoder(string token)
{
Expand Down
12 changes: 12 additions & 0 deletions AuthBot/Models/AuthResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.

return result;
}

public static AuthResult FromMSALAuthenticationResult(string authResult, Microsoft.Identity.Client.TokenCache tokenCache)
{
var result = new AuthResult
{
AccessToken = authResult,
ExpiresOnUtcTicks = DateTime.UtcNow.AddDays(1).Ticks,
TokenCache = tokenCache.Serialize()
};

return result;
}
}
}
//*********************************************************
Expand Down
2 changes: 1 addition & 1 deletion AuthBot/Models/AuthSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class AuthSettings
public static string RedirectUrl { get; set; }
public static string Mode { get; set; }
public static string[] Scopes { get; set; }

public static string Policy { get; set; }

}
}
Expand Down
37 changes: 37 additions & 0 deletions SampleB2CBot/App_Start/WebApiConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace SampleB2CBot
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Json settings
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};

// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
60 changes: 60 additions & 0 deletions SampleB2CBot/Controllers/MessagesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using SampleB2CBot.Dialogs;

namespace SampleB2CBot
{
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new ActionDialog());
}
else
{
this.HandleSystemMessage(activity);
}
return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
}

private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}

return null;
}
}
}
83 changes: 83 additions & 0 deletions SampleB2CBot/Dialogs/ActionDialog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@

namespace SampleB2CBot.Dialogs
{
using System;
using System.Threading;
using System.Threading.Tasks;
using AuthBot;
using AuthBot.Dialogs;
using AuthBot.Models;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

[Serializable]
public class ActionDialog : IDialog<string>
{
public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

public async Task TokenSample(IDialogContext context)
{
//endpoint b2c
var accessToken = await context.GetAccessToken(AuthSettings.Scopes);

if (string.IsNullOrEmpty(accessToken))
{
return;
}

await context.PostAsync($"Your access token is: {accessToken}");

context.Wait(MessageReceivedAsync);
}

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var message = await item;

if (message.Text == "logon")
{
//endpoint v2
if (string.IsNullOrEmpty(await context.GetAccessToken(AuthSettings.Scopes)))
{
await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, message, CancellationToken.None);
}
else
{
context.Wait(MessageReceivedAsync);
}
}
else if (message.Text == "echo")
{
await context.PostAsync("echo");

context.Wait(this.MessageReceivedAsync);
}
else if (message.Text == "token")
{
await TokenSample(context);
}
else if (message.Text == "logout")
{
await context.Logout();
context.Wait(this.MessageReceivedAsync);
}
else
{
context.Wait(MessageReceivedAsync);
}
}

private async Task ResumeAfterAuth(IDialogContext context, IAwaitable<string> result)
{
var message = await result;

await context.PostAsync(message);
context.Wait(MessageReceivedAsync);
}
}
}


Loading