How to ask user permission in private browser session? - c#

I noticed a very frustrating situation on Google OAuth2 where the email passed is different against the account actually connected to the system. Let me explain better, I wrote this method that ask user permission for access my app to user private Google Calendars:
public static CalendarService OAuth(string userName)
{
string[] scopes = new string[]
{
CalendarService.Scope.Calendar,
CalendarService.Scope.CalendarReadonly
};
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = "client id Google Developer Console",
ClientSecret = "Secret key Google Developer Console"
},
scopes,
userName,
CancellationToken.None,
new FileDataStore("Stored.Token")).Result;
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Application name"
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
Now someone already have understood the situation but I want to explain why this procedure is bad for me. Suppose that I want create an application that as the fist screen allow the user to insert personal email, this email should be used by the method OAuth as the parameter userName for ask user permission on Google Browser window.
Until here no problem, the user has entered the email and the application open Google Chrome browser for ask to him the permission to access to private calendars.
But, what's happean if the Google account connected actually in the Chrome browser is different against the email passed?
What's happean if the user that use the application grant the access with a different account connected and him doesn't noticed this?
The application will use a different account for upload the data and the user can thought that stay upload data on personal calendar. Someone have work around this situation, maybe opening Chrome, after UserCredential code block in a private browser, and if yes, in this case the token will stored in the folder specificed: AppData\Roaming\Stored.Token?
Practice example:
1. User type private email in my app: foo#gmail.com
2. App launch Chrome session and ask User permission, account acctually connected bar#gmail.com
3. User doesn't noticed this situation and grant my app to access to bar#gmail.com
4. My app will use bar#gmail.com for upload event, but the user thinks that the app stay using foo#gmail.com
5. The chaos.

Usage of different account can be prevented by performing the OAuth flow and updating private browser session with the granted token and scopes.
Reading through the Basics of Authentication, we have:
1. Registering your app
Every registered OAuth application is assigned a unique Client ID and Client Secret which should never be shared. When you register your application, you can fill out every piece of information except the Authorization callback URL, also considered as the most important piece of setting up your application. It's the callback URL where a user will be redirected after successful authentication.
2. Accepting user authorization
Your client ID and client secret keys come from your application's configuration page which was recommended to be stored as environment variables as shown in the sample code.
<html>
<head>
</head>
<body>
<p>
Well, hello there!
</p>
<p>
We're going to now talk to the GitHub API. Ready?
Click here to begin!</a>
</p>
<p>
If that link doesn't work, remember to provide your own Client ID!
</p>
</body>
</html>
Notice that the URL uses the scope query parameter to define the scopes requested by the application. For the sample code, we requested user:email scope for reading email addresses. After you click on the link you should be taken to Authorization page. and then will be redirected to a route specified in Callback URL. You will be provided with a temporary code value to be added in a POST HTTP request in exchange for an access_token then you'll be able to make authenticated requests as the logged user.
# fetch user information
auth_result = JSON.parse(RestClient.get('https://api.github.com/user',
{:params => {:access_token => access_token}}))
# if the user authorized it, fetch private emails
if has_user_email_scope
auth_result['private_emails'] =
JSON.parse(RestClient.get('https://api.github.com/user/emails',
{:params => {:access_token => access_token}}))
end
erb :basic, :locals => auth_result
And lastly,
3. Implementing "persistent" authentication
As recommended:
Since we're persisting scopes within the session, we'll need to handle cases when the user updates the scopes after we checked them, or revokes the token. To do that, we'll use a rescue block and check that the first API call succeeded, which verifies that the token is still valid. After that, we'll check the X-OAuth-Scopes response header to verify that the user hasn't revoked the user:email scope.
Implementing the code shown in developer github, we now have the authenticated method which checks if the user is already authenticated. If not, the authenticate method is called, which performs the OAuth flow and updates the session with the granted token and scopes.

Related

Create Microsoft Graph GraphServiceClient with user/password unattended

I am creating a console application that connects to Microsoft Graph using the Microsoft Graph API (as shown in https://github.com/microsoftgraph/console-csharp-connect-sample).
Everything is working fine, but I wonder if there is a way where I can authenticate a user (when I already know their user/password) without them needing to manually enter their credentials on the "Sing in to your account" window rendered on the desktop.
The idea is basically to run the application unattended, so there is no need for the user to be entering their credentials when the application starts. I can´t find any relevant information on the subject.
Is that even possible?
EDIT
After following the link #DanSilver posted about geting access without a user, I tried the sample suggested in that link (https://github.com/Azure-Samples/active-directory-dotnet-daemon-v2). Although that is an MVC application that forces users to authenticate (precisely what I wanted to avoid) I have managed to use part of the authentication code in that sample with my console application. After giving authorization to the application manually through a request to https://login.microsoftonline.com/myTenantId/adminconsent I can create a GraphServiceClient in my console app that connects to Graph without user interaction. So I mark the answer as valid.
Just in case someone is in the same situation, the GraphServiceclient is created as:
GraphServiceClient graphServiceClientApplication = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string clientId = "yourClientApplicationId";
string authorityFormat = "https://login.microsoftonline.com/{0}/v2.0";
string tenantId = "yourTenantId";
string msGraphScope = "https://graph.microsoft.com/.default";
string redirectUri = "msalXXXXXX://auth"; // Custom Redirect URI asigned in the Application Registration Portal in the native Application Platform
string clientSecret = "passwordGenerated";
ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(clientId, String.Format(authorityFormat, tenantId), redirectUri, new ClientCredential(clientSecret), null, new TokenCache());
AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(new string[] { msGraphScope });
string token = authResult.AccessToken;
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
));
One idea is using the "app only" authorization flow. The idea is that you can have long running apps access the Microsoft Graph without user authentication. The main difference is instead of the access token granting access to a particular user, it grants your app access to resources that you've consented to in advance. There will be no user login dialog and you can programmatically fetch access tokens to call the Graph API.
To reiterate that these tokens aren't for a particular user, consider making a GET request to 'https://graph.microsoft.com/v1.0/me'. This will return an error since the access token isn't for a particular user and "me" doesn't mean anything. Requests should be sent with full user ids "like graph.microsoft.com/users/someuser#contosos.com".
More information on this can be found at the Get access without a user documentation page.
Another idea is to let the user authenticate the first time they use your app and then store a refresh token. These tokens live longer (a few months IIRC) and then you won't need to prompt for user consent each time the app runs. Refresh tokens can be exchanged for access tokens that live 60 minutes and those can be used to call Graph API on behalf of users.
More info on refresh tokens: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user#5-use-the-refresh-token-to-get-a-new-access-token
I did want to come back out here and share, since I ran into this problem yesterday, and the idea of granting read/write mailbox access for my application... to EVERYONE'S EMAIL BOX IN THE ENTIRE ORGANIZATION... was way over the top for my needs. (And that is exactly what happens when you start talking about granting Application level permissions instead of delegated permissions to your registered app).
It's a simple use case: I had a nightly process that needed to automate sending of emails from a shared mailbox using a traditional AD service account.
Thankfully... even though they are on the march to eliminate passwords (lol)... someone at Microsoft still recognizes my use case, and it's lack of apples-to-apples alternatives in Azure AD. There is still an extension method we can lean on to get the job done:
private AuthenticationContext authContext = null;
authContext = new AuthenticationContext("https://login.microsoftonline.com/ourmail.onmicrosoft.com",
new TokenCache());
result = authContext.AcquireTokenAsync("https://graph.microsoft.com/",
"12345678-1234-1234-1234-1234567890",
new UserPasswordCredential(
Environment.GetEnvironmentVariable("UID", EnvironmentVariableTarget.User),
Environment.GetEnvironmentVariable("UPD", EnvironmentVariableTarget.User)
)).Result;
You can replace those GetEnvironmentVariable calls with your Username (UID) and Password (UPD). I just stuff them in the environment variables of the service account so I didn't have to check anything into source control.
AcquireTokenAsync is an extension method made available from the Microsoft.IdentityModel.Clients.ActiveDirectory namespace. From there, it's a simple business to fire up a GraphClient.
string sToken = result.AccessToken;
Microsoft.Graph.GraphServiceClient oGraphClient = new GraphServiceClient(
new DelegateAuthenticationProvider((requestMessage) => {
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("bearer", sToken);
return Task.FromResult(0);
}));
The last bit of magic was to add these permissions to Application registration I created in Azure AD (where that GUID came from). The application has be defined as a Public client (there's a radio button for that towards the bottom of the authentication tab). I added the following 5 DELEGATED permissions (NOT application permissions):
Microsoft Graph
1. Mail.ReadWrite.Shared
2. Mail.Send.Shared
3. User.Read
4. email
5. openid
Since user consents are actually blocked in our organization, another permissions admin had to review my application definition and then do an admin level grant of those rights, but once he did, everything lit up and worked like I needed: limited access by a service account to a single shared mailbox, with the actual security of that access being managed in Office 365 and not Azure AD.

Error while using ADAL.net AcquireTokenAsync call

I am exploring Azure Active Directory. I am trying to see whether I can use my own login page with custom user id/password controls to capture the user credentials and validate against Azure AD. I am using ADAL.net to implement this, however I get an error "parsing_wstrust_response_failed: Parsing WS-Trust response failed". I get this error on the last line of the below code.
The below is my code:
string AppIdURL = ConfigurationManager.AppSettings["AppIdUrl"];
UserCredential uc = new UserPasswordCredential("testuser#domain.com", "test123");
AuthenticationContext aContext = new AuthenticationContext(System.Configuration.ConfigurationManager.AppSettings["AADInstance"]);
AuthenticationResult result = aContext.AcquireTokenAsync(AppIdURL, ConfigurationManager.AppSettings["ClientId"], uc).Result;
Please first click here to view the constraints and limitations of the Resource Owner Password Credentials Grant flow . Base on your error message , is the user federated with WS-Trust ? Please provide more information about your current configuration to help us reproduce this error .
In fact, Resource Owner Password Credentials Grant flow is not recommend. This should only be used when there is a high degree of trust between the resource owner and the client (e.g., the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).
If your aim is to customize the sign-in page ,such as add company branding to your sign-in page , you could click here for how to customize the sign-in page .

invalid_grant - type = password: user or admin has not consented to use the application

I am getting a consent error when trying to obtain a token. Because of our application, we can't show an interactive dialog to give consent.
"AADSTS65001: The user or administrator has not consented to use the
application with ID <'my native client app id'>. Send an
interactive authorization request for this user and resource.
AuthenticationContext ctx = new AuthenticationContext(
string.Format("https://login.microsoftonline.com/{0}","mytenant.onmicrosoft.com"));
UserPasswordCredential cred = new UserPasswordCredential("login#mytenant.onmicrosoft.com", "Password");
var result = ctx.AcquireTokenAsync("my api uri", "my native client id", cred);
We are using the grant_type=password and client_id is a Native app id, and resource is the Web API app URI.
Permissions-wise, from the client app, a delegated permission has been given to access the api app and have also tried setting oauth2AllowImplicitFlow : true in the manifest.
All applications have been created in the new preview Azure AD section of the new portal (portal.azure.com)
Unfortunately if your application needs access to certain resources like the Graph API, you will need to prompt for consent at least one time.
Even if your app doesn't have an interactive login experience, you should be able to prompt this once to unblock your scenario in your tenant.
Use the following URL:
https://login.microsoftonline.com/<TenantID>/oauth2/authorize?client_id=<AppID>&response_type=code&redirect_uri=<RedirectURI>&resource=<ResourceURI>&prompt=admin_consent
You can see here we have just simply generated the login URL which would be generated as part of an interactive login experience. You will need to fill out your own specific data like Reply URL, App ID, Resource URI, etc...
Note that we added a final query string at the end where we are forcing a "consent" prompt. This should be done by an Administrator, who would be able to consent on behalf of the whole tenant. Once you have done that, the username/password flow should start working for you.
Also, as an additional note, implicit grant flow has nothing to do with consent.
Please read this section in the OAuth 2 spec:
https://www.rfc-editor.org/rfc/rfc6749#section-1.3.2
You should only use this setting if you are creating a single-page application with something like JavaScript; Otherwise, there are significant security concerns with this setting on applications that should not have it.

ADAL Azure AD Authentication user's login cached from different Azure AD session

Am currently setting up a web app hosted in Azure using Azure Active Directory for authentication, have almost worked all the kinks out but one issues remains. If a user has logged into a different Directory before hitting my sign-in page (in this case it is a University Office 365 login for email), the credential seems cached and Azure attempts to use it to log into my site, is there a way I can force the login screen on every sign-in and avoid re-use of a cached credential?
Project setup has been mainly standard, ASP.NET MVC architecture with default Azure Active Directory authentication settings.
Thanks!
A screenshot of the MS login page with error
Discovered the solution as soon as I posted. Implemented a signout and self-redirect to the sign-in method. Code is below:
public void SignIn(bool? signedOut)
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
// If the user is currently logged into another directory, log them out then attempt to
// reauthenticate under this directory
if (signedOut == null || signedOut == false)
{
HttpContext.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = Url.Action("SignIn", "Account", routeValues: new { signedOut = true }, protocol: Request.Url.Scheme) },
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
else
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}
Thanks anyway!
There are two better ways to handle this. First, use the tenant-specific Azure AD endpoint for your app. Your authority should be https://login.microsoftonline.com/<name-of-your-tenant>. That will ensure only users from your tenant can sign-in. But, if a user tries to sign-in with an account from a different tenant (by selecting an existing session or starting a new one), they will receive the error you screenshotted. No way to prevent that.
If you want to make sure the user enters their username/password every time they sign into your app, you can send the query parameter prompt=login in the sign-in request. But realize that this will break SSO for your users.

How to support NTLM authentication with fall-back to form in ASP.NET MVC?

How can I implement following in ASP.NET MVC application:
user opens intranet website
user is silently authenticated if possible
if NTLM authentication didn't worked out, show login form to user
user indicate login password and select domain from list of predefined domains
user is authenticated in code using AD
I know how to implement 4 and 5 but cannot find info on how to combine NTLM and forms.
So that NTLM native login/password dialog is never shown - transparent authentication or nice looking login page.
How should work?
Should user be asked login and password?
Can her current credentials (domain username) be used without asking to enter login and password?
UPDATE for these, investigating same problem:
When I was asking this I was not fully understand how NTLM authentication works internally.
Important thing here to understand is that if user's browser doesn't support NTLM properly or if NTLM support is disabled by user - server will never get chance to work around this.
How Windows authentication is working:
Client send a regular HTTP request to server
Server responds with HTTP status 401 and indication that NTLM authentication must be used to access resources
Client send NTLM Type1 message
Server responds with NTLM Type2 message with challenge
Client send Type3 message with response to challenge
Server responds with actual content requested
As you see, browser not supporting NTLM will not go to step (3), instead user will be shown IIS generated Error 401 page.
If user doesn’t have credentials, after cancelling NTLM authentication popup dialog window browser will not continue to (3) as well.
So we have no chance to automatically redirect users to custom login page.
The only option here is to have a “gateway” page where we decide if user should support NTLM and if so, redirect to NTLM protected home page.
And if not, show login form and allow authentication by manually entering login and password.
Decision is usually made based on users’ IP address and/or host name either by matching IP ranges or by checking table of predefined IPs.
This article might get you pointed in the right direction. Basically you have two apps in two virtual directories under the same host name. One app uses Forms authentication, one uses Windows. The one using Windows authentication creates a valid form authentication cookie and redirects to the second virtual directory.
ASP.NET Mixed Mode Authentication
I have this exact setup in production, I setup my portal to use FormsAuth and wrote a function that takes the visitors IP to look up the user account that is logged in to that IP / PC. Using the name I find (eg. DOMAIN\user), I verify the domain matches my domain and that the user name / account is valid in my FormsAth provider using Membership.GetUser(<user>). If this call returns a match and the user IsApproved I create a FormsAuthenticationTicket & cookie for the user. I have 400+ people on the network and this works perfectly, the only computers that still login are (1. Users without accounts in my portal, 2. A few MAC/Linux users, 3. Mobile users who did not boot on the network and had Group Policy enable their Firewall to High).
The catch to this solution is that it requires impersonation of a domain admin account to query the users PC, and that you use unmanaged code netapi32.dll.
Here is the code I use (external function calls not provided, for brevity). I've tried to simplify this a bit, since have LOTS of external calls.
string account = String.Empty;
string domain = String.Empty;
string user = String.Empty;
ImpersonateUser iu = new ImpersonateUser(); //Helper that Enabled Impersonation
if (iu.impersonateValidUser(StringHelper.GetAppSetting("DomainAccount"), StringHelper.GetAppSetting("DomainName"), StringHelper.GetEncryptedAppSetting("DomainAccountPassword")))
{
NetWorkstationUserEnum nws = new NetWorkstationUserEnum(); //Wrapper for netapi32.dll (Tested on Vista, XP, Win2K, Win2K3, Win2K8)
string host = nws.DNSLookup(Request.UserHostAddress); // netapi32.dll requires a host name, not an IP address
string[] users = nws.ScanHost(host); // Gets the users/accounts logged in
if (nws.ScanHost(host).Length > 0)
{
string workstationaccount = string.Empty;
if (host.IndexOf('.') == -1) // Pick which account to use, I have 99.9% success with this logic (only time doesn't work is when you run a interactive process as a admin e.g. Run As <process>).
{
workstationaccount = String.Format("{0}\\{1}$",StringHelper.GetAppSetting("DomainName"), host).ToUpper();
}
else
{
workstationaccount = String.Format("{0}\\{1}$", StringHelper.GetAppSetting("DomainName"), host.Substring(0, host.IndexOf('.'))).ToUpperInvariant();
}
account = users[users.Length - 1].Equals(workstationaccount) ? users[0] : users[users.Length - 1];
domain = account.Substring(0, account.IndexOf("\\"));
user = account.Substring(account.IndexOf("\\") + 1,
account.Length - account.IndexOf("\\") - 1);
}
iu.undoImpersonation(); // Disable Impersonation
}
Now using the account we grabbed in the first function/process, we now try to verify and decide if we should show a login or auto-login the user.
MembershipUser membershipUser = Membership.GetUser(user);
if (membershipUser != null && membershipUser.IsApproved)
{
string userRoles = string.Empty; // Get all their roles
FormsAuthenticationUtil.RedirectFromLoginPage(user, userRoles, true); // Create FormsAuthTicket + Cookie +
}
I wrote a blog post about this a long time ago, here is a link to the wrapper for netapi32.dll and my Impersonation helper that I provided in the post Source Code Download
You cannot have both NTLM and FormsAuthentication in the same ASP.NET application. You will need two different applications in separate virtual directories.

Categories