Fetching User by Id does not return - c#

I have made a successful connection to Azure AD (at least I hope so, unable to tell the details), and now I am trying to get some user's details. But the step-through debugger does not proceed over the following line:
IUser result = azureDirectoryClient.Users.GetByObjectId(someId).ExecuteAsync().Result;
That I got until here, no error is thrown and the function does not return - what does that tell me? How can I debug the issue further?

What do you catch when you debug this:
try
{
IUser result = azureDirectoryClient.Users.GetByObjectId(objectId).ExecuteAsync().Result;
}
catch(exception e)
{
console.white(e.message)
}
How do you connect to Azure AD? Make sure you get the accurate Accesstoken:
public static string GetTokenForApplication()
{
AuthenticationContext authenticationContext = new AuthenticationContext(Constants.AuthString, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(Constants.ClientId, Constants.ClientSecret);
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(Constants.ResourceUrl, clientCred);
string token = authenticationResult.AccessToken;
return token;
}
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri(https://graph.windows.net, TenantId),
async () => await GetTokenForApplication());

Don't forget to wait for the result somewhere using the await Keyword, also specify that the method is async so it runs asynchronously
public async Task<ActionResult> SomeAction()
{
IUser result = await azureDirectoryClient.Users.GetByObjectId(someId).ExecuteAsync();
return View(result);
}

Related

Calling MS Graph API has error CompactToken parsing failed with error code: 80049217

We implement to get the phone numbers being used in MFA of the signed-in user. We use password grant flow where we have a service account(with Global admin role) that will call MS Graph API on behalf of the user.
We are able to get the access token. However, when making a call to MS Graph encounters the error below.
Error:
ServiceException: Code: InvalidAuthenticationToken
Message: CompactToken parsing failed with error code: 80049217
MS Graph API call:
MicrosoftGraphClientSDK client = new MicrosoftGraphClientSDK();
var graphClient = client.GetAuthenticatedClient();
// Error encountered here:
var phones = await graphClient.Me.Authentication.PhoneMethods[{objectiD of the user}].Request().GetAsync();
This is how we get the access token in GetAuthenticatedClient
public MicrosoftGraphClientSDK()
{
_app_public = PublicClientApplicationBuilder.Create(clientID)
.WithAuthority("https://login.microsoftonline.com/{tenantID}")
.Build();
}
public Beta.GraphServiceClient GetAuthenticatedClient()
{
var accessToken = GetUserAccessTokenAsync();
var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.ToString());
return Task.FromResult(0);
});
_graphClient = new Beta.GraphServiceClient(delegateAuthProvider);
return _graphClient;
}
public async Task<string> GetUserAccessTokenAsync()
{
AuthenticationResult result;
var accounts = await _app_public.GetAccountsAsync();
if (accounts.Any())
{
result = await _app_public.AcquireTokenSilent(_scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
else
{
SecureString password = new SecureString();
foreach (char c in pass)
password.AppendChar(c);
result = await _app_public
.AcquireTokenByUsernamePassword(_scopes, username, password)
.ExecuteAsync();
}
return result.AccessToken;
}
I have search online about the error but could not get figure out the solution.
I appreciate your response. Thanks.

ADB2C - Handling the "Null user was passed in AcquiretokenSilent API" error when token cache expires

I've managed to configure my application to authenticate using ADB2C, and it seems to work fine. The ADB2C code implemented is a tweak of one of Microsoft's samples, in which they use a SessionTokenCache class to manage instances of TokenCache. In my application, I retrieve the access token as follows:
private async Task<string> _getAccessToken(IConfidentialClientCredentials credentials)
{
if (this.HasCredentials())
{
var clientCredential = new ClientCredential(credentials.ClientSecret);
var userId = this._getUserIdClaimValue();
var tokenCache = new SessionTokenCache(_httpContextResolver.Context, userId);
var confidentialClientApplication = new ConfidentialClientApplication(
credentials.ClientId,
credentials.Authority,
credentials.RedirectUri,
clientCredential,
tokenCache.GetInstance(),
null);
IAccount account = confidentialClientApplication.GetAccountsAsync().Result.FirstOrDefault();
if (account == null)
{
return "";
}
var authenticationResult = await confidentialClientApplication.AcquireTokenSilentAsync(
credentials.ApiScopes.Split(' '),
account,
credentials.Authority,
false);
return authenticationResult.AccessToken;
}
else
{
return "";
}
}
This method is used to get the access token and pass it in the request header of an HttpClient as follows:
...
using (var request = new HttpRequestMessage(HttpMethod.Get, address.AbsoluteUri))
{
if (this.HasCredentials())
{
string accessToken = await this._getAccessToken(_confidentialClientCredentials);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
using (HttpResponseMessage response = await this.SendAsync(request))
{
//result-processing logic
}
...
The problem is that when the app is restarted, the user remains authenticated through the ADB2C cookie, but confidentialClientApplication.GetAccountsAsync().Result.FirstOrDefault(); returns null. This probably happens because the token cache is destroyed on app restart, so I can probably use a Redis cache to fix.
My main issue however is how to handle the situation of having a null Account but being "authenticated" at the same time. How are my requests to my website being authenticated even though I have a null Account? Shouldn't it fail and redirect me to login page, for example?
I tried looking into Authorization filters, and using the following code to hook up to the auth process and validate if user is null there, but to no avail. The following events are not being called ever (this is in ConfigureServices):
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
.AddAzureADB2C(options => Configuration.Bind("ActiveDirectoryB2C", options))
.AddAzureADB2CBearer(options => Configuration.Bind("ActiveDirectoryB2C", options))
.AddCookie((options) => new CookieAuthenticationOptions
{
Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
// context.Principal gives you access to the logged-in user
// context.Properties.GetTokens() gives you access to all the tokens
return Task.CompletedTask;
},
OnSignedIn = context =>
{
return Task.CompletedTask;
}
}
});
It all feels a bit too abstracted for me to make any sense of what's going on. Either that, or I'm missing something fundamental.
Note: The error "Null user was passed in AcquiretokenSilent API. Pass in a user object or call acquireToken authenticate.
" is thrown if I try to pass the null account to the confidentialClientApplication.AcquireTokenSilentAsync() method.
I solved with this code:
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is Microsoft.Identity.Client.MsalUiRequiredException)
{
RedirectToAction("SignIn", "Account");
}
else {
//Do your logging
// ...
}
}
I'll search for a better solution.

Refreshing claimsPrincipal after changing roles

I'm having some issues with changing role in dotnetcore identity.
I have the following code.
private async Task SetRoleToX(ClaimsPrincipal claimsPrincipal, string X)
{
var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
var roles = await UserManager.GetRolesAsync(currentUser);
await UserManager.RemoveFromRolesAsync(currentUser, roles);
await UserManager.AddToRoleAsync(currentUser, X);
await SignInManager.RefreshSignInAsync(currentUser);
}
I cannot get the ClaimsPrincipal to update.
I have tried using sign in and sign out.
The role switch works fine if I manually sign in and out.
I have been searching the web and alot of people say this should work :(
Rather annoyingly all I had to do was send the token back with the request.
I cant believe i didn't think of it hope this helps someone.
Update with some code as requested
// In controller
public async Task SwapRole([FromBody]RoleSwapRequestDto dto)
{
await _service.SwapRole(
User,
dto.RoleName
);
return await AddCookieToResponse();
}
private async Task AddCookieToResponse()
{
// Make your token however your app does this (generic dotnet core stuff.)
var response = await _tokenService.RegenToken(User);
if (response.Data != null && response.Data.Authenticated && response.Data.TokenExpires.HasValue)
{
Response.Cookies.Append(AuthToken, response.Data.Token, new CookieOptions
{
HttpOnly = false,
Expires = response.Data.TokenExpires.Value
});
}
return response;
}
/// inside _service
public async Task SwapRole(ClaimsPrincipal claimsPrincipal, string X)
{
var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
var roles = await UserManager.GetRolesAsync(currentUser);
await UserManager.RemoveFromRolesAsync(currentUser, roles);
await UserManager.AddToRoleAsync(currentUser, X);
await SignInManager.RefreshSignInAsync(currentUser);
}

WebException on HTTP request while debugging

I have a ASP.NET project which involves sending HTTP requests via the Web-API Framework. The following exception is only raised when debugging:
The server committed a protocol violation. Section=ResponseStatusLine
The project runs perfectly if I "Start Without Debugging".
How should I resolve this exception?
Any help is appreciated!
Update
The problem seems related to the ASP.NET MVC Identity Framework.
To access other Web-API methods, the client application has to first POST a login request (The login request does not need to be secure yet, and so I am sending the username and password strings directly to the Web-API POST method). If I comment out the login request, no more exception is raised.
Below are the relevant code snippets:
The Post method:
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
AccountAccess ac = new AccountAccess();
public async Task<HttpResponseMessage> Post()
{
string result = await Request.Content.ReadAsStringAsync();
LoginMessage msg = JsonConvert.DeserializeObject<LoginMessage>(result);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var user = UserManager.Find(msg.username, msg.password);
if (user == null)
return response;
if (user.Roles == null)
return response;
var role = from r in user.Roles where (r.RoleId == "1" || r.RoleId == "2") select r;
if (role.Count() == 0)
{
return response;
}
bool task = await ac.LoginAsync(msg.username, msg.password);
response.Content = new StringContent(task.ToString());
return response;
}
The Account Access class (simulating the default AccountController in MVC template):
public class AccountAccess
{
public static bool success = false;
public AccountAccess()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountAccess(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public async Task<bool> LoginAsync(string username, string password)
{
var user = await UserManager.FindAsync(username, password);
if (user != null)
{
await SignInAsync(user, isPersistent: false);
return true;
}
else
{
return false;
}
}
~AccountAccess()
{
if (UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
}
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
}
Below are the relevant code snippets:
In client application:
public static async Task<List<T>> getItemAsync<T>(string urlAction)
{
message = new HttpRequestMessage();
message.Method = HttpMethod.Get;
message.RequestUri = new Uri(urlBase + urlAction);
HttpResponseMessage response = await client.SendAsync(message);
string result = await response.Content.ReadAsStringAsync();
List<T> msgs = JsonConvert.DeserializeObject<List<T>>(result);
return msgs;
}
In Web-API controller:
public HttpResponseMessage Get(string id)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
if (id == "ItemA")
{
List<ItemAMessage> msgs = new List<ItemAMessage>();
// some code...
response.Content = new StringContent(JsonConvert.SerializeObject(msgs));
}
else if (id == "ItemB")
{
List<ItemBMessage> msgs = new List<ItemBMessage>();
// some code...
response.Content = new StringContent(JsonConvert.SerializeObject(msgs));
}
return response;
}
Some observations I have:
I thought that I may need to send the request asynchronously (with the async-await syntax), but the exception still persists that way.
If I step through the code, the request does enter the HTTP method, but the code breaks at random line (Why?!) before returning the response, so I assume no response is being sent back.
I have tried the following solutions, as suggested in answers to similar questions, none of which works for me:
Setting useUnsafeHeaderParsing to true
Adding the header Keep-Alive: false
Changing the port setting of Skype (I don't have Skype, and port 80 and 443 are not occupied)
Additional information, in case they matter:
Mac OS running Windows 8.1 with VMware Fusion
Visual Studio 2013
.NET Framework 4.5
IIS Express Server
Update 2
The exception is resolved, but I am unsure of which modification did the trick. AFAIK, either one or both of the following fixed it:
I have a checkConnection() method, which basically sends a GET request and return true on success. I added await to the HttpClient.SendAsync() method and enforced async all the way up.
I retracted all code in the MainWindow constructor, except for the InitializeComponent() method, into the Window Initialized event handler.
Any idea?
Below are relevant code to the modifications illustrated above:
the checkConnectionAsync method:
public static async Task<bool> checkConnectionAsync()
{
message = new HttpRequestMessage();
message.Method = HttpMethod.Get;
message.RequestUri = new Uri(urlBase);
try
{
HttpResponseMessage response = await client.SendAsync(message);
return (response.IsSuccessStatusCode);
}
catch (AggregateException)
{
return false;
}
}
Window Initialized event handler (retracted from the MainWindow constructor):
private async void Window_Initialized(object sender, EventArgs e)
{
if (await checkConnectionAsync())
{
await loggingIn();
getItemA();
getItemB();
}
else
{
logMsg.Content = "Connection Lost. Restart GUI and try again.";
}
}
Update 3
Although this may be a little off-topic, I'd like to add a side note in case anyone else falls into this – I have been using the wrong authentication approach for Web-API to start with. The Web-API project template already has a built-in Identity framework, and I somehow "replaced" it with a rather simple yet broken approach...
This video is a nice tutorial to start with.
This article provides a more comprehensive explanation.
In the Client Application you are not awaiting task. Accessing Result without awaiting may cause unpredictable errors. If it only fails during Debug mode, I can't say for sure, but it certainly isn't the same program (extra checks added, optimizations generally not enabled). Regardless of when Debugging is active, if you have a code error, you should fix that and it should work in either modes.
So either make that function async and call the task with the await modifier, or call task.WaitAndUnwrapException() on the task so it will block synchronously until the result is returned from the server.
Make sure URL has ID query string with value either as Item A or Item B. Otherwise, you will be returning no content with Http status code 200 which could lead to protocol violation.
When you use SendAsync, you are required to provide all relevant message headers yourself, including message.Headers.Authorization = new AuthenticationHeaderValue("Basic", token); for example.
You might want to use GetAsync instead (and call a specific get method on the server).
Also, are you sure the exception is resolved? If you have some high level async method that returns a Task and not void, that exception might be silently ignored.

Get User Info after successful authentication using Windows Broker Authentication in Windows Metro App

I am working on Windows Broker Authentication.I can successfully authenticate in to the calling app and can comeback to the home page after authentication.
I am not able to get the user info (username) .I have tried but I get one message as written below.
A first chance exception of type 'System.Exception' occurred in mscorlib.dll
WinRT information: Response status code does not indicate success: 401 (Unauthorized).
Additional information: Unauthorized (401).
Response status code does not indicate success: 401 (Unauthorized).
If there is a handler for this exception, the program may be safely continued.
I have written my code below.Please friends help me.
private const string RESOURCE_NAME ="id_token";
public async Task<UserInfo> GetName(string accessToken)
{
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("OAuth", accessToken);
var result = await client.GetStringAsync(new Uri(loginUri));
var profileInformation =JsonObject.Parse(result).GetObject();
var name = profileInformation.GetNamedString("username");
return new UserInfo { Name = name };
}
catch (JsonException ex)
{
throw new JsonException(ex.message);
}
}
private async void btnHomeLogin_Click(object sender, RoutedEventArgs e)
{
string Scope = "openid profile";
var client = new OAuth2Client(new Uri(loginUri));
var startUri = client.CreateAuthorizeUrl(
ClientID,
RESOURCE_NAME,
Scope,
RedirectURI,
state,
nonce);
string Authresult;
try
{
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(startUri),new Uri(RedirectURI));
switch (webAuthenticationResult.ResponseStatus)
{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
//Successful authentication.
Authresult = webAuthenticationResult.ResponseData.ToString();
UserInfo userInfo = await GetName(RESOURCE_NAME);
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
//HTTP error.
Authresult = webAuthenticationResult.ResponseErrorDetail.ToString();
break;
default:
//Other error.
Authresult = webAuthenticationResult.ResponseData.ToString();
break;
}
}
catch (Exception ex)
{
//Authentication failed. Handle parameter, SSL/TLS, and Network Unavailable errors here.
Authresult = ex.Message;
}
}
If you are exactly using the above code, then based on the above, you are calling GetName function with a constant string (RESOURCE_NAME) instead of the actual AuthResult (accessToken) that was returned from the webAuthenticationResult. If the intention of calling the WebAuthenticationBroker is to get back an Access Token which should later be used with HttpClient, then you need to adjust your code accordingly and make use of the right access Token when calling the HttpClient code. Otherwise the 401 is not unexpected if you are not passing the right token.

Categories

Resources