When user removes "Works with Nest" for my client, the "withCancelBlock" is not called - nest-api

I'm using the following code to get notified when the user revokes permission from my client. Specifically, I expect the withCanelBlock to be called when the user revokes permission, but this block is never called.
[newFirebase observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
[self.subscribedURLs setObject:snapshot forKey:URL];
NSLog(#"%#", snapshot.value);
block(snapshot);
} withCancelBlock:^(NSError *error) {
NSLog(#"%s: permission revoked!!!!!", __PRETTY_FUNCTION__);
}
];

Related

DOMException: The request is not allowed by the user agent or the platform in the current context

When attempting to access a file using the getFile() method of a FileSystemFileHandle, this error can occur: DOMException: The request is not allowed by the user agent or the platform in the current context.
This code works:
async function getTheFile() {
// open file picker
[fileHandle] = await window.showOpenFilePicker(pickerOpts);
// get file contents
const fileData = await fileHandle.getFile();
}
However if you store the fileHandle (using IndexedDB, for example) with the intent to persist access to the file even after a page refresh, it will not work. After refreshing the page, the getFile() method will throw the DOMException error.
What's going on?
When the page is refreshed (or all tabs for the app are closed) the browser no longer has permission to access the file.
There is a queryPermission() method available for the FileSystemHandle that can be used to determine whether the file can be accessed before attempting to read it.
Example from a helpful web.dev article:
async function verifyPermission(fileHandle, readWrite) {
const options = {};
if (readWrite) {
options.mode = 'readwrite';
}
// Check if permission was already granted. If so, return true.
if ((await fileHandle.queryPermission(options)) === 'granted') {
return true;
}
// Request permission. If the user grants permission, return true.
if ((await fileHandle.requestPermission(options)) === 'granted') {
return true;
}
// The user didn't grant permission, so return false.
return false;
}
This function will return true once the permission === granted or re-prompt the user for access if permission is either denied or prompt.
Note that you will have to grant permissions each time you retrieve a handle from indexedDB, serializing seems to lose the permission

Using 2FA for password reset

My application uses Asp.Net Identity and sends a Two Factor code to my Auth app on login. This is pretty standard (as there lots of examples on the net) and uses the SendCode() method. My understanding is that the 'magic' is done by this line:
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
View("Error");
}
My requirement is to ensure the user goes through the same process of 2FA when they want to change their password after they have logged in.
My issue is that when the code to send the 2FA code is executed:
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
View("Error");
}
I receive the error 'UserID not found':
Server Error in '/MSPortal' Application.
UserId not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: UserId not found.
Source Error:
Line 555:
Line 556: // Generate the token and send it
Line 557: if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
Line 558: {
Line 559: return View("Error");
I know SendTwoFactorCodeAsync() calls GetVerifiedUserIdAsync() but my understanding is that the user is verified now that I have already logged in using 2FA.
Does anyone know why I would be getting this error?
Thanks.
I've worked around this by overriding SendTwoFactorCodeAsync() in IdentityConfig.cs. In this override, I first call GetVerifiedUserIdAsync() as per usual but then if that is 0 I get the User's ID from the Current HttpContext.
I am not stating this is the best way but it's what I have done thus far and its got me moving ahead in my aim of having 2FA for login, change password and forgot password.
The code (likely to go through some refactoring if I get feedback) is:
public override async Task<bool> SendTwoFactorCodeAsync(string provider)
{
int userId = 0;
try
{
userId = await GetVerifiedUserIdAsync();
if (userId == 0)
{
userId = Convert.ToInt32(HttpContext.Current.User.Identity.GetUserId());
}
if (userId == 0)
return false;
}
catch
{
return false;
}
var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider);
// See IdentityConfig.cs to plug in Email/SMS services to actually send the code
await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token);
return true;
//return base.SendTwoFactorCodeAsync(provider);
}

Sign out different user

I would like to be able to sign out some user that is logged in. By this I do not mean current user but some other user.
I, as an administrator, can deactivate or ban a user. At this point I would like to get this user and sign him out so when he makes his next request he gets redirected to log in page. After login attempt he would get a message why he cannot log in.
I am aware I can do it by writing my own authorization filter and go and fetch user from database each time but I would, if possible, like to avoid that.
Setting up authentication as follows hits mz OnValidatePrincipal each time a request is made but I do not know how to update exactly this user.
services.AddAuthentication("CookieAuthentication")
.AddCookie("CookieAuthentication", options => {
options.LoginPath = "/Login";
options.Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(async (a) =>
{
var expired = a.Principal.FindFirst(System.Security.Claims.ClaimTypes.Expired);
if(expired != null && bool.Parse(expired.Value))
{
a.RejectPrincipal();
return;
}
await Task.CompletedTask;
})
};
});
I am also aware that I could write my own middleware and keep some kind of list of all the users that have logged in. That list could than be easily updated by an administrator and checked by the previous event.
What I would like to know is, can I get an instance of other logged user and can I than alter its claims?

Azure Active Directory Application Permission Change Delay

I am using Azure Active Directory to give my application access to the Microsoft Graph API.
When I make permission changes (e.g., read/write access for various types of data) I am noticing a delay from when the changes are saved and when I am able to access the new data through the API. I do notice, however, that after some time my API calls start to work. My questions are
Is this expected behavior?
Is there documentation somewhere that explains what permissions are needed for each Microsoft Graph API request?
Note that I am requesting a new token after making each permission change, before making the relevant API request.
When you changed your scopes (if you use Azure to manage thoses Autorizations) you have to request new consent from your users. Be sure to be able to call "one time" the ADAL AcquireTocken method, with the PromptBehavior.Always parameter.
I think it will be enough to refresh your consents and make your new scopes availables.
Here is a macro code I use :
if (mustRefreshBecauseScopesHasChanged)
{
authResult = await authContext.AcquireTokenAsync(GraphResourceId, ClientId, AppRedirectURI, PromptBehavior.Always);
}
else
{
authResult = await authContext.AcquireTokenSilentAsync(GraphResourceId, ClientId);
if (authResult.Status != AuthenticationStatus.Success && authResult.Error == "failed_to_acquire_token_silently")
authResult = await authContext.AcquireTokenAsync(GraphResourceId, ClientId, AppRedirectURI, PromptBehavior.Auto);
}
if (authResult.Status != AuthenticationStatus.Success)
{
if (authResult.Error == "authentication_canceled")
{
// The user cancelled the sign-in, no need to display a message.
}
else
{
MessageDialog dialog = new MessageDialog(string.Format("If the error continues, please contact your administrator.\n\nError: {0}\n\n Error Description:\n\n{1}", authResult.Error, authResult.ErrorDescription), "Sorry, an error occurred while signing you in.");
await dialog.ShowAsync();
}
}
For the scopes permissions détails, you will find them here :
http://graph.microsoft.io/en-us/docs/authorization/permission_scopes

Azure Mobile Service - Windows Account Back Arrow gives a InvalidOperationException

WAMS: Microsoft authentication.
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-store-dotnet-get-started-users/
Changed from Facebook to MicrosoftAccount
PROBLEM: When I click on the back arrow (to escape the login) It should still be in the while loop and force another popup never allowing the user to have success. Instead it hit the
catch (InvalidOperationException)
private MobileServiceUser user;
private async System.Threading.Tasks.Task AuthenticateAsync()
{
while (user == null)
{
string message;
try
{
user = await App.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
message =
string.Format("You are now logged in - {0}", user.UserId);
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}
When you cancel the authentication page, the awaited call to LoginAsync will throw the InvalidOperationException. That's expected - you asked the SDK to login, the login operation didn't succeed, so you get an exception. When the exception is thrown, the assignment to the user field doesn't happen, so it retains its original value (null), which is why the loop continues. If you have a breakpoint in the catch block, and continue after hitting the breakpoint (F5), it should prompt with the authentication again.

Resources