I'm trying to do a simple query from the Google Vault API using JSON credentials provided from the Google API console for a service account. I'm getting a 400 response (Invalid Request / Invalid Argument) with the message:
The user does not belong to a G Suite customer.
Does anyone know what I might be doing wrong? Do I have to augment the JSON with anything to indicate our G Suite Account?
Thanks in advance.
The code's fairly straight forward:
matter_id = 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
vault = Google::Apis::VaultV1::VaultService.new
scope = 'https://www.googleapis.com/auth/ediscovery.readonly'
vault.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('./xxxxxxxxxx.json'),
scope: scope)
vault.authorization.fetch_access_token!
m = vault.get_matter(matter_id)
Update -- this has been resolved. You have to update sub after you create the credentials to impersonate a user.
matter_id = 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
vault = Google::Apis::VaultV1::VaultService.new
scope = 'https://www.googleapis.com/auth/ediscovery.readonly'
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('./xxxxxxxxxx.json'),
scope: scope)
credentials.update!(sub: 'user#domain.com')
vault.authorization = credentials
vault.authorization.fetch_access_token!
m = vault.get_matter(matter_id)
Working through sending gmail with the newer google-api-ruby-client in a rails 4 application.
require 'google/apis/gmail_v1'
Gmail = Google::Apis::GmailV1
class MailService
def initialize(params)
#params = params
end
def call
message = Gmail::Message.new
service = Gmail::GmailService.new
message.raw = (redacted)
service.request_options.authorization = current_user.token.fresh_token
result = service.send_user_message(current_user.email, message)
end
end
And this is the result from the call to the API:
Sending HTTP post https://www.googleapis.com/gmail/v1/users/me/messages/send?
200
#<Hurley::Response POST https://www.googleapis.com/gmail/v1/users/me/messages/send == 200 (63 bytes) 858ms>
Success - #<Google::Apis::GmailV1::Message:0x007fc9cf9b52dd
#id="15096369c05cdb1d",
#thread_id="15096369c05cdb1d">
The raw message sends without issue from the API explorer but when executed from my application I get a bounce email in my inbox. In the above example the redacted sample is a valid RFC 2822 formatted base-64 url safe string and fresh_token represents the oauth2 access token for the current user.
A look at the bounced mail
Bounce <nobody#gmail.com>
2:43 PM (19 minutes ago)
to me
An error occurred. Your message was not sent.
Anyone have any thoughts? It seems like perhaps my (sender) email is being picked up in the raw message but not the recipient... Though I suppose the API could be forwarding the bounce based on my oauth access token.
I very much appreciate any help. Thanks!
EDIT: Solution was to pass the RFC 2822 string as raw property without base64 encoding.
Steve Bazyl seems to be correct. The documentation on send_user_message is wrong as of (0.9.13). For raw, it says: "The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied. Corresponds to the JSON property raw." As far as I can tell, this is simply incorrect.
I encountered this issue when updating from google-api-client 0.8 to 0.9 and removing the base64 encoding solved the problem. I.e. call in 0.8:
response = #service.execute(
api_method: api.users.messages.to_h['gmail.users.messages.send'],
body_object: {
raw: Base64.urlsafe_encode64(mail.to_s)
},
parameters: {
userId: 'me',
}
)
became
message = { raw: mail.to_s }
res = #service.send_user_message('me', message, {})
in 0.9.
Reported as https://github.com/google/google-api-ruby-client/issues/474.
I am using Azure AD to provision and license new users in O365 and it works beautifully, however I need some further O365 functionality (i.e. being able to export a user's contacts). I noticed that there are permissions for your app to do this:
I get can a bearer token to do all my other REST calls similar to this code (in ruby using httparty):
domain = "example.com"
api_version = "1.5"
auth_url = "https://login.windows.net/#{domain}/oauth2/token?api-version=#{api_version}"
auth_body = {"grant_type" => "client_credentials", "client_id" => #client_id, "client_secret" => #client_secret}
auth_headers = {"Content-Type" => "application/x-www-form-urlencoded"}
token_resp = HTTParty.post(auth_url, :headers => auth_headers, :body => auth_body)
bearer_token = "Bearer #{token_resp['access_token']}"
It works great on calls to https://graph.windows.net/ however when I try to make calls on O365 Exchange:
request_headers={"Authorization" => bearer_token, "Content-Type"=>"application/json"}
request = HTTParty.get("https://outlook.office365.com/api/v1.0/users/user#example.com", :headers => request_headers)
or
request = HTTParty.get("https://api.office.com/discovery/v1.0/me/services", :headers => request_headers)
I get the following response:
HTTParty::Response:0x7fea2f8b0e40 parsed_response={"error"=>{"code"=>"-2147024891,
System.UnauthorizedAccessException", "message"=>"Access denied. You do
not have permission to perform this action or access this
resource."}}, #response=#, #headers={"cache-control"=>["private, max-age=0"],
"transfer-encoding"=>["chunked"],
"content-type"=>["application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8"], "expires"=>["Mon, 29 Dec 2014 19:27:04 GMT"], "last-modified"=>["Tue,
13 Jan 2015 19:27:04 GMT"], "server"=>["Microsoft-IIS/8.0"],
"x-correlationid"=>["595d3bd9-94f7-40fe-b4ed-c3a28cc74cdb"],
"x-usersessionid"=>["595d3bd9-94f7-40fe-b4ed-c3a28cc74cdb"],
"x-officefe"=>["OdcFrontEnd_IN_10"],
"x-officeversion"=>["16.0.3705.3001"],
"x-officecluster"=>["scus-odc.officeapps.live.com"], "p3p"=>["CP=\"CAO
DSP COR ADMa DEV CONi TELi CUR PSA PSD TAI IVDi OUR SAMi BUS DEM NAV
STA UNI COM INT PHY ONL FIN PUR\""], "odata-version"=>["4.0"],
"x-aspnet-version"=>["4.0.30319"], "x-powered-by"=>["ASP.NET"],
"date"=>["Tue, 13 Jan 2015 19:27:03 GMT"], "connection"=>["close"]}>
Am I missing something here? How can I use a bearer token for my app to access the Exchange Online APIs? Is there any docs for this? I can't seem to find anything on the subject.
"have full access to a user's mailbox" requires administrative access. I would suggest turning that permission off and giving it another go.
Currently, the user themselves needs to sign in and grant your app access to the Contacts API. We are working on releasing app-only permissions (similar to what Graph has now) shortly.
I am using C3 & the latest twitterizer api. I have managed to get the user to authenticate & authorize my twitter application after which I persist only the access_token, access_token_secret and access_token_verifier.
The problem I have now is that when the user returns ( at a later stage, cookies removed / expired ), they identify themselves using our own credentials system, and then I attempt to see if their twitter credentials are still valid. I do this by calling the following method
OAuthTokens t = new OAuthTokens();
t.ConsumerKey = "XXX"; // my applications key
t.ConsumerSecret = "XXX";// my applications secret
t.AccessToken = "XXX";// the users token from the DB
t.AccessTokenSecret = "XXX";//the users secret from the DB
TwitterResponse<TwitterUser> resp = TwitterAccount.VerifyCredentials(tokens);
This is the error I get : "error":"Could not authenticate with OAuth.","request":"/1/account/verify_credentials.json"
I know my tokens are valid because if I call this method :
TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, CORRECT_SCREEN_NAME_HERE);
with my screen name passed in and the same OAuth tokens, it returns correctly.
Any Ideas?
C# -> v4.0.30319
Twitterizer -> 2.4.0.2028
In your code, you're defining tokens as t, but when you call VerifyCredentials you're passing it tokens. Is that just an error in your sample code?
It has been asked, and answered for .NET, but now it's time to get an answer for native Win32 code:
How do i validate a Windows username and password?
i asked this question before for managed code. Now it's time for the native solution.
It needs to be pointed the pitfalls with some of the more commonly proposed solutions:
Invalid Method 1. Query Active Directory with Impersonation
A lot of people suggest querying the Active Directory for something. If an exception is thrown, then you know the credentials are not valid - as is suggested in this stackoverflow question.
There are some serious drawbacks to this approach however:
You are not only authenticating a domain account, but you are also doing an implicit authorization check. That is, you are reading properties from the AD using an impersonation token. What if the otherwise valid account has no rights to read from the AD? By default all users have read access, but domain policies can be set to disable access permissions for restricted accounts (and or groups).
Binding against the AD has a serious overhead, the AD schema cache has to be loaded at the client (ADSI cache in the ADSI provider used by DirectoryServices). This is both network, and AD server, resource consuming - and is too expensive for a simple operation like authenticating a user account.
You're relying on an exception failure for a non-exceptional case, and assuming that means invalid username and password. Other problems (e.g. network failure, AD connectivity failure, memory allocation error, etc) are then mis-intrepreted as authentication failure.
The use of the DirectoryEntry class is .NET is an example of an incorrect way to verify credentials:
Invalid Method 1a - .NET
DirectoryEntry entry = new DirectoryEntry("persuis", "iboyd", "Tr0ub4dor&3");
object nativeObject = entry.NativeObject;
Invalid Method 1b - .NET #2
public static Boolean CheckADUserCredentials(String accountName, String password, String domain)
{
Boolean result;
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, accountName, password))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
String filter = String.Format("(&(objectCategory=user)(sAMAccountName={0}))", accountName);
searcher.Filter = filter;
try
{
SearchResult adsSearchResult = searcher.FindOne();
result = true;
}
catch (DirectoryServicesCOMException ex)
{
const int SEC_E_LOGON_DENIED = -2146893044; //0x8009030C;
if (ex.ExtendedError == SEC_E_LOGON_DENIED)
{
// Failed to authenticate.
result = false;
}
else
{
throw;
}
}
}
}
As well as querying Active Directory through an ADO connection:
Invalid Method 1c - Native Query
connectionString = "Provider=ADsDSOObject;
User ID=iboyd;Password=Tr0ub4dor&3;
Encrypt Password=True;Mode=Read;
Bind Flags=0;ADSI Flag=-2147483648';"
SELECT userAccountControl
FROM 'LDAP://persuis/DC=stackoverflow,DC=com'
WHERE objectClass='user' and sAMAccountName = 'iboyd'
These both fail even when your credentials are valid, but you do not have permission to view your directory entry:
Invalid Method 2. LogonUser Win32 API
Others have suggested using the LogonUser() API function. This sounds nice, but unfortunatly the calling user sometimes needs a permission ususally only given to the operating system itself:
The process calling LogonUser requires
the SE_TCB_NAME privilege. If the
calling process does not have this
privilege, LogonUser fails and
GetLastError returns
ERROR_PRIVILEGE_NOT_HELD.
In some
cases, the process that calls
LogonUser must also have the
SE_CHANGE_NOTIFY_NAME privilege
enabled; otherwise, LogonUser fails
and GetLastError returns
ERROR_ACCESS_DENIED. This privilege is
not required for the local system
account or accounts that are members
of the administrators group. By
default, SE_CHANGE_NOTIFY_NAME is
enabled for all users, but some
administrators may disable it for
everyone.
Handing out the "Act as a part of the operating system" privelage is not something you want to do willy-nilly - as Microsoft points out in a knowledge base article:
...the process that is calling
LogonUser must have the SE_TCB_NAME
privilege (in User Manager, this is
the "Act as part of the Operating
System" right). The SE_TCB_NAME
privilege is very powerful and
should not be granted to any arbitrary user just so that they can
run an application that needs to
validate credentials.
Additionally, a call to LogonUser() will fail if a blank password is specified.
Valid .NET 3.5 Method - PrincipalContext
There is a validation method, only available in .NET 3.5 and newer, that allows authentication by a user without performing an authorization check:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "stackoverflow.com"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("iboyd", "Tr0ub4dor&3")
}
Unfortunately this code is only available in .NET 3.5 and later.
It's time to find the native equivalent.
Here is Microsoft's recommendation.
As for the other answers, I'm not really sure why you're shooting them down. You are complaining about (relatively edge case) failures while trying to validate credentials, but if you are going to actually do something with those credentials then that operation is just going to fail anyway. If you are not going to actually do something with those credentials, then why do you need to validate them in the first place? It seems like a somewhat contrived situation, but obviously I don't know what you're trying to accomplish.
For the native equivalnt of your valid .NET solution see this MSDN page and ldap_bind
Howerver I think that LogonUser is the right API for the task when use with LOGON32_LOGON_NETWORK. Note that the limitation of SE_CHANGE_NOTIFY_NAME is only for Windows 2000 (so Windows XP and newer do not require this priviledge) and that by default SE_CHANGE_NOTIFY_NAME is enabled for all users. Also the MSDN page says
The SE_TCB_NAME privilege is not required for this function unless you are logging onto a Passport account.
In this case you are logging onto an AD account so SE_TCB_NAME is not required.
I might as well post the native code to validate a set of Windows credentials. It took a while to implement.
function TSSPLogon.LogonUser(username, password, domain: string; packageName: string='Negotiate'): HRESULT;
var
ss: SECURITY_STATUS;
packageInfo: PSecPkgInfoA;
cbMaxToken: DWORD;
clientBuf: PByte;
serverBuf: PByte;
authIdentity: SEC_WINNT_AUTH_IDENTITY;
cbOut, cbIn: DWORD;
asClient: AUTH_SEQ;
asServer: AUTH_SEQ;
Done: boolean;
begin
{
If domain is blank will use the current domain.
To force validation against the local database use domain "."
sspiProviderName is the same of the Security Support Provider Package to use. Some possible choices are:
- Negotiate (Preferred)
Introduced in Windows 2000 (secur32.dll)
Selects Kerberos and if not available, NTLM protocol.
Negotiate SSP provides single sign-on capability called as Integrated Windows Authentication.
On Windows 7 and later, NEGOExts is introduced which negotiates the use of installed
custom SSPs which are supported on the client and server for authentication.
- Kerberos
Introduced in Windows 2000 and updated in Windows Vista to support AES) (secur32.dll)
Preferred for mutual client-server domain authentication in Windows 2000 and later.
- NTLM
Introduced in Windows NT 3.51 (Msv1_0.dll)
Provides NTLM challenge/response authentication for client-server domains prior to
Windows 2000 and for non-domain authentication (SMB/CIFS)
- Digest
Introduced in Windows XP (wdigest.dll)
Provides challenge/response based HTTP and SASL authentication between Windows and non-Windows systems where Kerberos is not available
- CredSSP
Introduced in Windows Vista and available on Windows XP SP3 (credssp.dll)
Provides SSO and Network Level Authentication for Remote Desktop Services
- Schannel
Introduced in Windows 2000 and updated in Windows Vista to support stronger AES encryption and ECC (schannel.dll)
Microsoft's implementation of TLS/SSL
Public key cryptography SSP that provides encryption and secure communication for
authenticating clients and servers over the internet. Updated in Windows 7 to support TLS 1.2.
If returns false, you can call GetLastError to get the reason for the failure
}
// Get the maximum authentication token size for this package
ss := sspi.QuerySecurityPackageInfoA(PAnsiChar(packageName), packageInfo);
if ss <> SEC_E_OK then
begin
RaiseWin32Error('QuerySecurityPackageInfo "'+PackageName+'" failed', ss);
Result := ss;
Exit;
end;
try
cbMaxToken := packageInfo.cbMaxToken;
finally
FreeContextBuffer(packageInfo);
end;
// Initialize authorization identity structure
ZeroMemory(#authIdentity, SizeOf(authIdentity));
if Length(domain) > 0 then
begin
authIdentity.Domain := PChar(Domain);
authIdentity.DomainLength := Length(domain);
end;
if Length(userName) > 0 then
begin
authIdentity.User := PChar(UserName);
authIdentity.UserLength := Length(UserName);
end;
if Length(Password) > 0 then
begin
authIdentity.Password := PChar(Password);
authIdentity.PasswordLength := Length(Password);
end;
AuthIdentity.Flags := SEC_WINNT_AUTH_IDENTITY_ANSI; //SEC_WINNT_AUTH_IDENTITY_UNICODE
ZeroMemory(#asClient, SizeOf(asClient));
ZeroMemory(#asServer, SizeOf(asServer));
//Allocate buffers for client and server messages
GetMem(clientBuf, cbMaxToken);
GetMem(serverBuf, cbMaxToken);
try
done := False;
try
// Prepare client message (negotiate)
cbOut := cbMaxToken;
ss := Self.GenClientContext(#asClient, authIdentity, packageName, nil, 0, clientBuf, cbOut, done);
if ss < 0 then
begin
RaiseWin32Error('Error generating client context for negotiate', ss);
Result := ss;
Exit;
end;
// Prepare server message (challenge).
cbIn := cbOut;
cbOut := cbMaxToken;
ss := Self.GenServerContext(#asServer, packageName, clientBuf, cbIn, serverBuf, cbOut, done);
if ss < 0 then
begin
{
Most likely failure: AcceptServerContext fails with SEC_E_LOGON_DENIED in the case of bad username or password.
Unexpected Result: Logon will succeed if you pass in a bad username and the guest account is enabled in the specified domain.
}
RaiseWin32Error('Error generating server message for challenge', ss);
Result := ss;
Exit;
end;
// Prepare client message (authenticate).
cbIn := cbOut;
cbOut := cbMaxToken;
ss := Self.GenClientContext(#asClient, authIdentity, packageName, serverBuf, cbIn, clientBuf, cbOut, done);
if ss < 0 then
begin
RaiseWin32Error('Error generating client client for authenticate', ss);
Result := ss;
Exit;
end;
// Prepare server message (authentication).
cbIn := cbOut;
cbOut := cbMaxToken;
ss := Self.GenServerContext(#asServer, packageName, clientBuf, cbIn, serverBuf, cbOut, done);
if ss < 0 then
begin
RaiseWin32Error('Error generating server message for authentication', ss);
Result := ss;
Exit;
end;
finally
//Free resources in client message
if asClient.fHaveCtxtHandle then
sspi.DeleteSecurityContext(#asClient.hctxt);
if asClient.fHaveCredHandle then
sspi.FreeCredentialHandle(#asClient.hcred);
//Free resources in server message
if asServer.fHaveCtxtHandle then
sspi.DeleteSecurityContext(#asServer.hctxt);
if asServer.fHaveCredHandle then
sspi.FreeCredentialHandle(#asServer.hcred);
end;
finally
FreeMem(clientBuf);
FreeMem(serverBuf);
end;
Result := S_OK;
end;
Note: Any code released into public domain. No attribution required.
There is a win32 API function called ldap_bind_s. The ldap_bind_s function authenticates a client
against LDAP. See MSDN documentation for more information.
I authenticated user, by username & password like this :
username is user sn attribute value in Ldap server, like U12345
userDN is user DistinguishedName in LdapServer
public bool AuthenticateUser(string username, string password)
{
try
{
var ldapServerNameAndPort = "Servername:389";
var userDN = string.Format("CN=0},OU=Users,OU=MyOU,DC=MyDC,DC=com",username);
var conn = new LdapConnection(ldapServerNameAndPort)
{
AuthType = AuthType.Basic
};
conn.Bind(new NetworkCredential(userDN , password));
return true;
}
catch (Exception e)
{
return false;
}
}