I'm currently working on an application where i need to get all the users from the company's azure ad
I manage to make a select and get all users into the ResultText textblock.
i now use the DisplayBasicTokenInfo() to fill a textbox but it only returns 1 username and that's my own. Now what i want to do is make a list of all the users and load these into a combobox via DisplayBasicTokenInfo.
I don't know if this is the best solution but it is what i found. The end goal for this is that i want every Displayname to be a comboboxItem
This is the code i have so far.
public partial class TestGraphApi : Window
{
//Set the API Endpoint to Graph 'users' endpoint
string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/users?$select=displayName";
//Set the scope for API call to user.read.all
string[] _scopes = new string[] { "user.read.all" };
public TestGraphApi()
{
InitializeComponent();
}
/// <summary>
/// Call AcquireTokenAsync - to acquire a token requiring user to sign-in
/// </summary>
private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
{
AuthenticationResult authResult = null;
var app = App.PublicClientApp;
ResultText.Text = string.Empty;
TokenInfoText.Text = string.Empty;
var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
try
{
authResult = await app.AcquireTokenSilent(_scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
authResult = await app.AcquireTokenInteractive(_scopes)
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
}
catch (MsalException msalex)
{
ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
return;
}
if (authResult != null)
{
ResultText.Text = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);
DisplayBasicTokenInfo(authResult);
}
}
/// <summary>
/// Perform an HTTP GET request to a URL using an HTTP Authorization header
/// </summary>
/// <param name="url">The URL</param>
/// <param name="token">The token</param>
/// <returns>String containing the results of the GET operation</returns>
public async Task<string> GetHttpContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// Display basic information contained in the token
/// </summary>
private void DisplayBasicTokenInfo(AuthenticationResult authResult)
{
TokenInfoText.Text = "";
if (authResult != null)
{
TokenInfoText.Text += $"{authResult.Account.Username}";
}
}
}
You use TokenInfoText.Text += $"{authResult.Account.Username}"; to set TokenInfoText in your case.
authResult.Account.Username just returned the signed-in user which used to get access token, but not the users the API returned.
If you just want to get all displayNames, you could decode the ResultText.Text and get the values. Convert JSON String to JSON Object c#.
Also you can use Microsoft Graph SDK to get the users.
private async Task<List<User>> GetUsersFromGraph()
{
// Create Graph Service Client, refer to https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.Build();
AuthorizationCodeProvider authenticationProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);
GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);
// Create a bucket to hold the users
List<User> users = new List<User>();
// Get the first page
IGraphServiceUsersCollectionPage usersPage = await graphServiceClient
.Users
.Request()
.Select(u => new {
u.DisplayName
})
.GetAsync();
// Add the first page of results to the user list
users.AddRange(usersPage.CurrentPage);
// Fetch each page and add those results to the list
while (usersPage.NextPageRequest != null)
{
usersPage = await usersPage.NextPageRequest.GetAsync();
users.AddRange(usersPage.CurrentPage);
}
return users;
}
Related
I have a condition set to where if there's a cached token, it will use that or else it will either look for passed in credentials or prompt for credentials. Even after entering my credentials once via AcquireTokenInteractive() and running the program again, it still prompts for credentials. If I only have AcquireTokenSilent(), I get a reference error for the token variable because nothing is passed to it. It is either not caching my token or it is not fetching my cached token properly, but I'm not sure how to troubleshoot either. According to the MSDocs https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-acquire-cache-tokens it should do the caching automatically.
For the time being, I commented out the AcquireTokenByUsernamePassword() for troubleshooting purposes.
static async Task<GraphServiceClient> Auth()
{
string[] scopes = new string[] { "user.read" };
string token = null;
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(ConfigurationManager.AppSettings["clientId"])
.Build();
AuthenticationResult result = null;
var accounts = await app.GetAccountsAsync();
if (accounts.Any())
{
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
else
{
try
{
///var securePassword = new SecureString();
///foreach (char c in "dummy") // you should fetch the password
/// securePassword.AppendChar(c); // keystroke by keystroke
/// result = await app.AcquireTokenByUsernamePassword(scopes,"joe#contoso.com",securePassword).ExecuteAsync();
}
catch (MsalException)
{
///
}
try
{
result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}
catch (MsalException)
{
///
}
}
token = result.AccessToken;
// Use the token
GraphServiceClient graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
Yes, you are right. The SDK will do the caching automatically. I tested it by creating a console app:
class Program
{
static void Main(string[] args)
{
string flag = "Y";
IPublicClientApplication app = PublicClientApplicationBuilder.Create("60ef0838-f145-4f00-b7ba-a5af7f31cc3c").Build();
string[] scopes = new string[] { "api://4a673722-5437-4663-bba7-5f49372e06ba/Group.All","openid" };
do
{
List<IAccount> list = app.GetAccountsAsync().GetAwaiter().GetResult().ToList();
Console.WriteLine("Checking cache");
if (list.Count > 0)
{
Console.WriteLine($"Find {list.Count}");
list.ForEach(_ =>
{
Console.WriteLine($"Acquire a new token for {_.Username}");
AuthenticationResult result = app.AcquireTokenSilent(scopes, _).WithForceRefresh(true).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().Result;
Console.WriteLine($"New token -> {result.AccessToken}");
});
}
else
{
Console.WriteLine("No cache");
try
{
var securePassword = new SecureString();
// Test AcquireTokenByUsernamePassword
foreach (char c in "**********") securePassword.AppendChar(c);
AuthenticationResult result = app.AcquireTokenByUsernamePassword(scopes, "jack#hanxia.onmicrosoft.com", securePassword).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().GetAwaiter().GetResult();
// Test AcquireTokenInteractive
//AuthenticationResult result = app.AcquireTokenInteractive(scopes).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().Result;
Console.WriteLine(result.Account.Username + " -> " + result.AccessToken);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
}
}
Console.Write("Continue? Y/N:");
flag = Console.ReadLine();
} while (flag.Trim().ToUpper().Equals("Y"));
Console.ReadLine();
}
}
The result:
I have a web API method which creates secrets on azure key vault and it works fine, I also have a delete method that deletes an entity and its associated secrets, however, this method is not deleting the key on azure key vault, but it's not throwing an exception either!
Here the helper methods:
public async Task OnCreateSecretAsync(string name, string value)
{
Message = "Your application description page.";
int retries = 0;
bool retry = false;
try
{
/* The below 4 lines of code shows you how to use AppAuthentication library to set secrets from your Key Vault*/
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var result = await keyVaultClient.SetSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name, value)
.ConfigureAwait(false);
SecretIdentifier = result.Id;
/* The below do while logic is to handle throttling errors thrown by Azure Key Vault. It shows how to do exponential backoff which is the recommended client side throttling*/
do
{
long waitTime = Math.Min(GetWaitTime(retries), 2000000);
result = await keyVaultClient.SetSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name, value)
.ConfigureAwait(false);
Message = result.Id;
retry = false;
}
while (retry && (retries++ < 10));
}
/// <exception cref="KeyVaultErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
catch (KeyVaultErrorException keyVaultException)
{
Message = keyVaultException.Message;
if ((int)keyVaultException.Response.StatusCode == 429)
retry = true;
}
}
/// <summary>
/// Deletes secrets
/// </summary>
/// <param name="name">Secret</param>
/// <param name="value">Value</param>
/// <returns></returns>
public async Task OnDeleteSecretAsync(string name)
{
Message = "Your application description page.";
int retries = 0;
bool retry = false;
try
{
/* The below 4 lines of code shows you how to use AppAuthentication library to set secrets from your Key Vault*/
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var result = await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name)
.ConfigureAwait(false);
SecretIdentifier = result.Id;
/* The below do while logic is to handle throttling errors thrown by Azure Key Vault. It shows how to do exponential backoff which is the recommended client side throttling*/
do
{
long waitTime = Math.Min(GetWaitTime(retries), 2000000);
result = await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name)
.ConfigureAwait(false);
Message = result.Id;
retry = false;
}
while (retry && (retries++ < 10));
}
/// <exception cref="KeyVaultErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
catch (KeyVaultErrorException keyVaultException)
{
Message = keyVaultException.Message;
if ((int)keyVaultException.Response.StatusCode == 429)
retry = true;
}
}
And here the methods where I call them from:
public async Task<IHttpActionResult> AddGlobalDesignTenant([FromBody]GlobalDesignTenant globaldesigntenant)
{
var telemetry = new TelemetryClient();
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
string domainUrl = globaldesigntenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0].Remove(0, 8);
globaldesigntenant.TenantName = tenantName;
var globalDesignTenantStore = CosmosStoreHolder.Instance.CosmosStoreGlobalDesignTenant;
byte[] data = Convert.FromBase64String(globaldesigntenant.base64CertFile);
var cert = new X509Certificate2(
data,
globaldesigntenant.CertificatePassword,
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);
try
{
using (var cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(globaldesigntenant.TestSiteCollectionUrl,
globaldesigntenant.Applicationid,
globaldesigntenant.TenantName + ".onmicrosoft.com",
cert, AzureEnvironment.Production))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
}
}
catch (Exception ex)
{
return BadRequest("Cant authenticate with those credentials");
}
KeyVaultHelper keyVaultHelperPFX = new KeyVaultHelper();
await keyVaultHelperPFX.OnCreateSecretAsync("GlobalDesignTenantPFXFileBAse64"+ tenantName, globaldesigntenant.base64CertFile);
globaldesigntenant.SecretIdentifierBase64PFXFile = keyVaultHelperPFX.SecretIdentifier;
KeyVaultHelper keyVaultHelperPassword = new KeyVaultHelper();
await keyVaultHelperPassword.OnCreateSecretAsync("GlobalDesignTenantCertPassword" + tenantName, globaldesigntenant.CertificatePassword);
globaldesigntenant.SecretIdentifieCertificatePassword = keyVaultHelperPassword.SecretIdentifier;
globaldesigntenant.CertificatePassword = string.Empty;
globaldesigntenant.base64CertFile = string.Empty;
var added = await globalDesignTenantStore.AddAsync(globaldesigntenant);
return Ok(added);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
public async Task<IHttpActionResult> DeleteGlobalDesignTenant(string id)
{
var telemetry = new TelemetryClient();
try
{
var globalDesignTenantStore = CosmosStoreHolder.Instance.CosmosStoreGlobalDesignTenant;
var globalDesignTenant = await globalDesignTenantStore.FindAsync(id, "globaldesigntenants");
KeyVaultHelper keyVaultHelperPFX = new KeyVaultHelper();
await keyVaultHelperPFX.OnDeleteSecretAsync("GlobalDesignTenantPFXFileBAse64" + globalDesignTenant.TenantName);
KeyVaultHelper keyVaultHelperPassword = new KeyVaultHelper();
await keyVaultHelperPassword.OnDeleteSecretAsync("GlobalDesignTenantCertPassword" + globalDesignTenant.TenantName);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await globalDesignTenantStore.RemoveAsync(globalDesignTenant);
return Ok(result);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
Based on my test, await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name) will delete the secret with specified name.
So, please set a break-point at the delete calling. Then run your application to see if it hits, and check if the parameters were expected values.
I have two projects. One is an Identity server 4 who handle users and authentication. The second need to use the first to login and ask for a token to access an API.
When I need to refresh the token I don't now how to handle the new access token. How I can set to the authentification asp dot net core the new token. All the refresh process are made on a AuthorizationHandler.
I tried to modify the claims on identity but doesnt work. I tried to stock access token and refresh token inside my own cookie but I have trouble because when I refresh the token I can only use them at the next request (I didn't achieve to modify the request.cookies only the response.cookies.
public static async Task SetToken(TokenKind token,string value, HttpContext context)
{
context.Response.Cookies.Append(GetTokenCookieName(token), value);
}
public static async Task<string> GetRefreshTokenAsync(HttpContext context)
{
return await SearchToken(TokenKind.Refresh,context);
}
private static async Task<string> SearchToken(TokenKind token, HttpContext context)
{
var tokenName = GetTokenName(token);
var test = context.Request.Cookies;
var apiToken = context.Request.Cookies.FirstOrDefault(x => x.Key == GetTokenCookieName(token)).Value;
if (apiToken == null)
{
// Save token into cookie
var tokenValue = await context.GetTokenAsync(GetTokenName(TokenKind.Access));
await SetToken(TokenKind.Access, tokenValue, context);
var refreshTokenValue = await context.GetTokenAsync(GetTokenName(TokenKind.Refresh));
await SetToken(TokenKind.Refresh, refreshTokenValue, context);
switch (token)
{
case TokenKind.Access:
return tokenValue;
case TokenKind.Refresh:
return refreshTokenValue;
default:
return null;
break;
}
}
else
{
return apiToken;
}
}
private async Task<bool> RefreshToken(AuthorizationFilterContext mvcContext, HttpClient client)
{
var refreshToken = await TokenUtils.GetRefreshTokenAsync(mvcContext.HttpContext);
//await mvcContext.HttpContext.GetTokenAsync("refresh_token");
var variables = new Dictionary<string, string>
{
{ "grant_type", "refresh_token" },
{ "client_id", _configuration["ApplicationOptions:ClientId"] },
{ "client_secret", _configuration["ApplicationOptions:ClientSecret"] },
{ "refresh_token", refreshToken }
};
var content = new FormUrlEncodedContent(variables);
var url = _configuration["ApplicationOptions:AuthorizeServer"] + "/connect/token";
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode == false)
{
var errorString = await response.Content.ReadAsStringAsync();
var errorData = JsonConvert.DeserializeObject<dynamic>(errorString);
return false;
}
var contentAsString = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<dynamic>(contentAsString);
var newAccessToken = (string)responseData.access_token;
var newRefreshToken = (string)responseData.refresh_token;
await TokenUtils.SetAccessToken(newAccessToken, mvcContext.HttpContext);
await TokenUtils.SetRefreshToken(newRefreshToken, mvcContext.HttpContext);
var result = await mvcContext.HttpContext.AuthenticateAsync();
if (result.Succeeded)
{
result.Properties.StoreTokens(new List<AuthenticationToken>
{
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.AccessToken,
Value = newAccessToken
},
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.RefreshToken,
Value = newRefreshToken
}
});
return true;
}
else
{
return false;
}
}
I would like to know what is the good pratice to store (or replace the actual access token) with the .net core authentification. I'm sure I'm not doing it the right way. At the end I want to handle correctly my token and my refresh token for not ask the user to login again. Now with my solution my project will denied the access when it need to refresh the token and next request will be granted (because the cookie need to be resend from the user).
Thank to Ruard van Elburg I found the solution (here's the complete answer)
And that's what I used to replace my tokens:
// Save the information in the cookie
var info = await mvcContext.HttpContext.AuthenticateAsync("Cookies");
info.Properties.UpdateTokenValue("refresh_token", newRefreshToken);
info.Properties.UpdateTokenValue("access_token", newAccessToken);
info.Properties.UpdateTokenValue("expires_at", expiresAt.ToString("o", CultureInfo.InvariantCulture));
await mvcContext.HttpContext.SignInAsync("Cookies", info.Principal, info.Properties);
In ASP.NET MVC app, I am trying to implement authentication against external OIDC service. For my testing I am using IdentityServer3 (https://identityserver.github.io/Documentation/) and public OIDC demo server: https://mitreid.org/
I cloned this sample from GitHub: https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/MVC%20Authentication
Then added the following code to register the public OIDC server as external login provider:
private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "<AuthTypeName>",
Authority = "https://mitreid.org/",
Caption = "MIT Test Server",
ClientId = "<Client Id>",
ClientSecret = "<Client Secret>",
RedirectUri = "https://localhost:44319/", //NOT SURE WHAT TO PUT HERE
ResponseType = "code",
Scope = "openid email profile",
SignInAsAuthenticationType = signInAsType
});
}
The code works, i get the option to login via external OIDC server. The browser redirects to the external server login page and when login and password is entered, the consent page is shown. However, after the browser navigates back to https://localhost:44319/ the user is not authenticated - User.Identity.IsAuthenticated is false.
Question: What should be correct value of RedirectUri property? Does OpenIdConnect middleware have capability to parse the authantication info passed in from external server or it must be coded manually? Is there any sample code how to do this?
I was studying the code and debugging quite a few hours (I am new to this) and I learned that:
This problem is related to OpenIdConnect OWIN Middleware implemented by Microsoft (https://github.com/aspnet/AspNetKatana/tree/dev/src/Microsoft.Owin.Security.OpenIdConnect).
The middleware from Microsoft expect that the OIDC server sends the message using HTTP POST, but the MIT server does HTTP GET
The middleware from Microsoft expect that there is id token along with code in the message obtained from OIDC server, but the MIT server sends only the code.
Looks like the RedirectUri can be any path under /identity because the middleware method AuthenticateCoreAsync() is hit on every request and it does compare request path to configured Options.CallbackPath (which is set from RedirectURI)
So I just had to implement the standard authorization code flow - exchange the code for id token, get claims, create authentication ticket and redirect to IdentityServer /identity/callback endpoint. When I've done this, everything started working. IdentityServer is awesome!
I inherited new set of classes from OpenIdConnect middleware and did override some methods. The key method is async Task<AuthenticationTicket> AuthenticateCoreAsync() in OpenIdConnectAuthenticationHandler. I pasted the code below in case it would help to someone.
public class CustomOidcHandler : OpenIdConnectAuthenticationHandler
{
private const string HandledResponse = "HandledResponse";
private readonly ILogger _logger;
private OpenIdConnectConfiguration _configuration;
public CustomOidcHandler(ILogger logger) : base(logger)
{
_logger = logger;
}
/// <summary>
/// Invoked to process incoming authentication messages.
/// </summary>
/// <returns>An <see cref="AuthenticationTicket"/> if successful.</returns>
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
// Allow login to be constrained to a specific path. Need to make this runtime configurable.
if (Options.CallbackPath.HasValue && Options.CallbackPath != (Request.PathBase + Request.Path))
return null;
OpenIdConnectMessage openIdConnectMessage = null;
if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
openIdConnectMessage = new OpenIdConnectMessage(Request.Query);
if (openIdConnectMessage == null)
return null;
ExceptionDispatchInfo authFailedEx = null;
try
{
return await CreateAuthenticationTicket(openIdConnectMessage).ConfigureAwait(false);
}
catch (Exception exception)
{
// We can't await inside a catch block, capture and handle outside.
authFailedEx = ExceptionDispatchInfo.Capture(exception);
}
if (authFailedEx != null)
{
_logger.WriteError("Exception occurred while processing message: ", authFailedEx.SourceException);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
if (Options.RefreshOnIssuerKeyNotFound && authFailedEx.SourceException.GetType() == typeof(SecurityTokenSignatureKeyNotFoundException))
Options.ConfigurationManager.RequestRefresh();
var authenticationFailedNotification = new AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
{
ProtocolMessage = openIdConnectMessage,
Exception = authFailedEx.SourceException
};
await Options.Notifications.AuthenticationFailed(authenticationFailedNotification).ConfigureAwait(false);
if (authenticationFailedNotification.HandledResponse)
return GetHandledResponseTicket();
if (authenticationFailedNotification.Skipped)
return null;
authFailedEx.Throw();
}
return null;
}
private async Task<AuthenticationTicket> CreateAuthenticationTicket(OpenIdConnectMessage openIdConnectMessage)
{
var messageReceivedNotification =
new MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
{
ProtocolMessage = openIdConnectMessage
};
await Options.Notifications.MessageReceived(messageReceivedNotification).ConfigureAwait(false);
if (messageReceivedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (messageReceivedNotification.Skipped)
{
return null;
}
// runtime always adds state, if we don't find it OR we failed to 'unprotect' it this is not a message we
// should process.
AuthenticationProperties properties = GetPropertiesFromState(openIdConnectMessage.State);
if (properties == null)
{
_logger.WriteWarning("The state field is missing or invalid.");
return null;
}
// devs will need to hook AuthenticationFailedNotification to avoid having 'raw' runtime errors displayed to users.
if (!string.IsNullOrWhiteSpace(openIdConnectMessage.Error))
{
throw new OpenIdConnectProtocolException(
string.Format(CultureInfo.InvariantCulture,
openIdConnectMessage.Error,
"Exception_OpenIdConnectMessageError", openIdConnectMessage.ErrorDescription ?? string.Empty,
openIdConnectMessage.ErrorUri ?? string.Empty));
}
// tokens.Item1 contains id token
// tokens.Item2 contains access token
Tuple<string, string> tokens = await GetTokens(openIdConnectMessage.Code, Options)
.ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(openIdConnectMessage.IdToken))
openIdConnectMessage.IdToken = tokens.Item1;
var securityTokenReceivedNotification =
new SecurityTokenReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context,
Options)
{
ProtocolMessage = openIdConnectMessage,
};
await Options.Notifications.SecurityTokenReceived(securityTokenReceivedNotification).ConfigureAwait(false);
if (securityTokenReceivedNotification.HandledResponse)
return GetHandledResponseTicket();
if (securityTokenReceivedNotification.Skipped)
return null;
if (_configuration == null)
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled)
.ConfigureAwait(false);
// Copy and augment to avoid cross request race conditions for updated configurations.
TokenValidationParameters tvp = Options.TokenValidationParameters.Clone();
IEnumerable<string> issuers = new[] {_configuration.Issuer};
tvp.ValidIssuers = tvp.ValidIssuers?.Concat(issuers) ?? issuers;
tvp.IssuerSigningTokens = tvp.IssuerSigningTokens?.Concat(_configuration.SigningTokens) ?? _configuration.SigningTokens;
SecurityToken validatedToken;
ClaimsPrincipal principal =
Options.SecurityTokenHandlers.ValidateToken(openIdConnectMessage.IdToken, tvp, out validatedToken);
ClaimsIdentity claimsIdentity = principal.Identity as ClaimsIdentity;
var claims = await GetClaims(tokens.Item2).ConfigureAwait(false);
AddClaim(claims, claimsIdentity, "sub", ClaimTypes.NameIdentifier, Options.AuthenticationType);
AddClaim(claims, claimsIdentity, "given_name", ClaimTypes.GivenName);
AddClaim(claims, claimsIdentity, "family_name", ClaimTypes.Surname);
AddClaim(claims, claimsIdentity, "preferred_username", ClaimTypes.Name);
AddClaim(claims, claimsIdentity, "email", ClaimTypes.Email);
// claims principal could have changed claim values, use bits received on wire for validation.
JwtSecurityToken jwt = validatedToken as JwtSecurityToken;
AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, properties);
if (Options.ProtocolValidator.RequireNonce)
{
if (String.IsNullOrWhiteSpace(openIdConnectMessage.Nonce))
openIdConnectMessage.Nonce = jwt.Payload.Nonce;
// deletes the nonce cookie
RetrieveNonce(openIdConnectMessage);
}
// remember 'session_state' and 'check_session_iframe'
if (!string.IsNullOrWhiteSpace(openIdConnectMessage.SessionState))
ticket.Properties.Dictionary[OpenIdConnectSessionProperties.SessionState] = openIdConnectMessage.SessionState;
if (!string.IsNullOrWhiteSpace(_configuration.CheckSessionIframe))
ticket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame] =
_configuration.CheckSessionIframe;
if (Options.UseTokenLifetime)
{
// Override any session persistence to match the token lifetime.
DateTime issued = jwt.ValidFrom;
if (issued != DateTime.MinValue)
{
ticket.Properties.IssuedUtc = issued.ToUniversalTime();
}
DateTime expires = jwt.ValidTo;
if (expires != DateTime.MinValue)
{
ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
}
ticket.Properties.AllowRefresh = false;
}
var securityTokenValidatedNotification =
new SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context,
Options)
{
AuthenticationTicket = ticket,
ProtocolMessage = openIdConnectMessage,
};
await Options.Notifications.SecurityTokenValidated(securityTokenValidatedNotification).ConfigureAwait(false);
if (securityTokenValidatedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (securityTokenValidatedNotification.Skipped)
{
return null;
}
// Flow possible changes
ticket = securityTokenValidatedNotification.AuthenticationTicket;
// there is no hash of the code (c_hash) in the jwt obtained from the server
// I don't know how to perform the validation using ProtocolValidator without the hash
// that is why the code below is commented
//var protocolValidationContext = new OpenIdConnectProtocolValidationContext
//{
// AuthorizationCode = openIdConnectMessage.Code,
// Nonce = nonce
//};
//Options.ProtocolValidator.Validate(jwt, protocolValidationContext);
if (openIdConnectMessage.Code != null)
{
var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
{
AuthenticationTicket = ticket,
Code = openIdConnectMessage.Code,
JwtSecurityToken = jwt,
ProtocolMessage = openIdConnectMessage,
RedirectUri =
ticket.Properties.Dictionary.ContainsKey(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey)
? ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey]
: string.Empty,
};
await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification)
.ConfigureAwait(false);
if (authorizationCodeReceivedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (authorizationCodeReceivedNotification.Skipped)
{
return null;
}
// Flow possible changes
ticket = authorizationCodeReceivedNotification.AuthenticationTicket;
}
return ticket;
}
private static void AddClaim(IEnumerable<Tuple<string, string>> claims, ClaimsIdentity claimsIdentity, string key, string claimType, string issuer = null)
{
string subject = claims
.Where(it => it.Item1 == key)
.Select(x => x.Item2).SingleOrDefault();
if (!string.IsNullOrWhiteSpace(subject))
claimsIdentity.AddClaim(
new System.Security.Claims.Claim(claimType, subject, ClaimValueTypes.String, issuer));
}
private async Task<Tuple<string, string>> GetTokens(string authorizationCode, OpenIdConnectAuthenticationOptions options)
{
// exchange authorization code at authorization server for an access and refresh token
Dictionary<string, string> post = null;
post = new Dictionary<string, string>
{
{"client_id", options.ClientId},
{"client_secret", options.ClientSecret},
{"grant_type", "authorization_code"},
{"code", authorizationCode},
{"redirect_uri", options.RedirectUri}
};
string content;
using (var client = new HttpClient())
{
var postContent = new FormUrlEncodedContent(post);
var response = await client.PostAsync(options.Authority.TrimEnd('/') + "/token", postContent)
.ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
// received tokens from authorization server
var json = JObject.Parse(content);
var accessToken = json["access_token"].ToString();
string idToken = null;
if (json["id_token"] != null)
idToken = json["id_token"].ToString();
return new Tuple<string, string>(idToken, accessToken);
}
private async Task<IEnumerable<Tuple<string, string>>> GetClaims(string accessToken)
{
string userInfoEndpoint = Options.Authority.TrimEnd('/') + "/userinfo";
var userInfoClient = new UserInfoClient(new Uri(userInfoEndpoint), accessToken);
var userInfoResponse = await userInfoClient.GetAsync().ConfigureAwait(false);
var claims = userInfoResponse.Claims;
return claims;
}
private static AuthenticationTicket GetHandledResponseTicket()
{
return new AuthenticationTicket(null, new AuthenticationProperties(new Dictionary<string, string>() { { HandledResponse, "true" } }));
}
private AuthenticationProperties GetPropertiesFromState(string state)
{
// assume a well formed query string: <a=b&>OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey=kasjd;fljasldkjflksdj<&c=d>
int startIndex = 0;
if (string.IsNullOrWhiteSpace(state) || (startIndex = state.IndexOf("OpenIdConnect.AuthenticationProperties", StringComparison.Ordinal)) == -1)
{
return null;
}
int authenticationIndex = startIndex + "OpenIdConnect.AuthenticationProperties".Length;
if (authenticationIndex == -1 || authenticationIndex == state.Length || state[authenticationIndex] != '=')
{
return null;
}
// scan rest of string looking for '&'
authenticationIndex++;
int endIndex = state.Substring(authenticationIndex, state.Length - authenticationIndex).IndexOf("&", StringComparison.Ordinal);
// -1 => no other parameters are after the AuthenticationPropertiesKey
if (endIndex == -1)
{
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex).Replace('+', ' ')));
}
else
{
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex, endIndex).Replace('+', ' ')));
}
}
}
public static class CustomOidcAuthenticationExtensions
{
/// <summary>
/// Adds the <see cref="OpenIdConnectAuthenticationMiddleware"/> into the OWIN runtime.
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="openIdConnectOptions">A <see cref="OpenIdConnectAuthenticationOptions"/> contains settings for obtaining identities using the OpenIdConnect protocol.</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
public static IAppBuilder UseCustomOidcAuthentication(this IAppBuilder app, OpenIdConnectAuthenticationOptions openIdConnectOptions)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (openIdConnectOptions == null)
throw new ArgumentNullException(nameof(openIdConnectOptions));
return app.Use(typeof(CustomOidcMiddleware), app, openIdConnectOptions);
}
}
and in Startup.cs
public class Startup
{
....
public void Configuration(IAppBuilder app)
{
....
private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseCustomOidcAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "<name>",
Authority = "<OIDC server url>",
Caption = "<caption>",
ClientId = "<client id>",
ClientSecret = "<client secret>",
// might be https://localhost:44319/identity/<anything>
RedirectUri = "https://localhost:44319/identity/signin-customoidc",
ResponseType = "code",
Scope = "openid email profile address phone",
SignInAsAuthenticationType = signInAsType
}
);
}
....
}
....
}
I'm having troubles .NET Core Web API app authentication.
I want to:
1) Authenticate user with Google on Mobile App (currently iOS)
2) Using this authentication, create user record in database using AspNetCore.Identity and Entity Framework Core
3) Using same authentication, call Google Calendar API from .NET Core server
So far I figured out how to implement 1 and 3, but can't wrap my head around number 2.
My understanding is that to sign in user authenticated with third-party, due to documentation, you need to use SignInManager instance method ExternalLoginSignInAsync. It takes two arguments:
login provider (should be simple stirng as "Google") and unique provider key. My problem is that I can't find anywhere where can I get one.
Here is the list of all things I receive from Google Sign In result on mobile app:
Here is the method I try to call in.
// POST api/signup
[HttpPost]
public async Task<bool> Post([FromBody]string authorizationCode, [FromBody]string userId)
{
var tokenFromAuthorizationCode = await GetGoogleTokens(userId, authorizationCode);
var result = await signInManager.ExternalLoginSignInAsync(
"Google", tokenFromAuthorizationCode.IdToken, false);
if (result.Succeeded)
return true;
var externalLoginInfo = new ExternalLoginInfo(
ClaimsPrincipal.Current, "Google", tokenFromAuthorizationCode.IdToken, null);
return await SignInUser(externalLoginInfo);
}
private async Task<bool> SignInUser(ExternalLoginInfo info)
{
var newUser = new AppUser { Email = "test#test.com", UserName = "TestUser" };
var identResult = await userManager.CreateAsync(newUser);
if (identResult.Succeeded)
{
identResult = await userManager.AddLoginAsync(newUser, info);
if (identResult.Succeeded)
{
await signInManager.SignInAsync(newUser, false);
return true;
}
}
return false;
}
private async Task<TokenResponse> GetGoogleTokens(string userId, string authorizationCode)
{
TokenResponse token;
try
{
// TODO: Save access and refresh token to AppUser object
token = await authFlow.Flow.ExchangeCodeForTokenAsync(
userId, authorizationCode, "http://localhost:60473/signin-google", CancellationToken.None);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return token;
}
My question is: is it a correct path if you're building authentication via REST API, and if so, where could I get Google's provider key?
Thanks in advance.
Well apparently, provider key is just user id from Google.
Here is the solution that worked for me:
[HttpPost]
public async Task<AppUser> Post([FromBody]GoogleSignInCredentials credentials)
{
// 1. get user id from idToken
var oauthService = new Oauth2Service(new BaseClientService.Initializer { ApiKey = "{your api key}" });
var tokenInfoRequest = oauthService.Tokeninfo();
tokenInfoRequest.IdToken = credentials.IdToken;
var userInfo = await tokenInfoRequest.ExecuteAsync();
// 2. get access_token and refresh_token with new id and authorization code
var tokenFromAuthorizationCode = await GetGoogleTokens(userInfo.UserId, credentials.AuthorizationCode);
// 3. check if user exists
var result = await _signInManager.ExternalLoginSignInAsync(
"Google", userInfo.UserId, false);
if (result.Succeeded)
return await _userManager.FindByEmailAsync(userInfo.Email);
// 4. create user account
var externalLoginInfo = new ExternalLoginInfo(
ClaimsPrincipal.Current, "Google", userInfo.UserId, null);
// 5. fetch user
var createdUser = await SignInUser(externalLoginInfo, userInfo.Email);
if (createdUser != null)
{
createdUser.GoogleAccessToken = tokenFromAuthorizationCode.AccessToken;
createdUser.GoogleRefreshToken = tokenFromAuthorizationCode.RefreshToken;
var updateResult = await _userManager.UpdateAsync(createdUser);
if (updateResult.Succeeded)
return createdUser;
return null;
}
return null;
}
private async Task<AppUser> SignInUser(ExternalLoginInfo info, string email)
{
var newUser = new AppUser { Email = email, UserName = email };
var identResult = await _userManager.CreateAsync(newUser);
if (identResult.Succeeded)
{
identResult = await _userManager.AddLoginAsync(newUser, info);
if (identResult.Succeeded)
{
await _signInManager.SignInAsync(newUser, false);
return await _userManager.FindByEmailAsync(email);
}
}
return null;
}
private async Task<TokenResponse> GetGoogleTokens(string userId, string authorizationCode)
{
return await _authFlow.Flow.ExchangeCodeForTokenAsync(
userId, authorizationCode, "http://localhost:60473/signin-google", CancellationToken.None);
}