Amplify "Unable to verify secret hash for client" - amazon-cognito

We have been using Amplify and Cognito to register our users for an Angular6 application deployed to Lambda. The client wanted to transition from email to username as primary user identification. So we created a new user pool / client. I don't have visibility into the configuration settings, I was simply given new user pool, identity pool, and client id's. Then I changed the code for application signup to look like this:
return from(Auth.signUp({
'username': username, // was email
'password': password,
attributes: { // added these
'email': email,
'phone_number': phone_number,
'family_name': name,
'birthdate': DOB,
'custom:last_4_ssn': SSN // custom attribute
}}));
The response I'm getting with no other changes made is: Unable to verify secret hash for client. Google claims the problem is that secretAccess is currently an unsupported configuration, but the guy who has access to these services swears to me that nowhere is secretAccess configured in our setup.
I apologize for not having access to the configuration, but is there any other possible reason to receive this error?

That error is probably originating from the fact that the app client you are connected to has an associated secret key. When you create a user pool app client, it generates a secret by default:
Right now, with React-Native Amplify you have to use an app client that does not have a secret key generated. So when you create a new app client with your desired attributes, make sure the "Generate client secret" box is unchecked.

The solution is to pass secret_hash along with the adminAuthInitiate Request. And to calculate the secret hash you can use the following method:
public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) {
final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
SecretKeySpec signingKey = new SecretKeySpec(
userPoolClientSecret.getBytes(StandardCharsets.UTF_8),
HMAC_SHA256_ALGORITHM);
try {
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
mac.update(userName.getBytes(StandardCharsets.UTF_8));
byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(rawHmac);
} catch (Exception e) {
throw new RuntimeException("Error while calculating ");
}
}
How to Pass Secret_Hash
Map<String, String> authParams = new HashMap<>(2);
authParams.put("USERNAME", <username>);
authParams.put("PASSWORD", <password>);
authParams.put("SECRET_HASH", calculateSecretHash(cognitoClientId, cognitoClientSecret, <username>));
AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
.withClientId(userPool.getClientId()).withUserPoolId(userPool.getUserPoolId())
.withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH).withAuthParameters(authParams);
AdminInitiateAuthResult result = cognito.adminInitiateAuth(authRequest);
auth = result.getAuthenticationResult();

Related

How to get username from Exchange identity token?

I'm writing an Add-in for Office365/Outlook. The Add-in runs on a web-server that presents information from a third-party system. I need to make sure it only presents information related to the username (or email address) logged in. I've successfully sent and validated the Exchange identity token on my server, using the PHP example code provided by Microsoft:
https://dev.office.com/docs/add-ins/outlook/use-php-to-validate-an-identity-token
My problem is that the identity token does not contain any username or email adress, the closest I get is "msexchuid", but I can't make any sense out of that numeric user identifier in the third-party system.
On the client side the Add-in javascript can get a username and email via "Office.context.mailbox.userProfile", however I don't just want to forward that to my web server as it could be faked.
Is there a way to make the Identity token contain the username/email (that would be great!), or is it possible from my web server's server side PHP script lookup further user details based on the identity token?
The id token is used to intend to integrate with third-party application for SSO. As you mentioned that it only include a unique id of Exchange.
As a workaround, we can get from the callback token via the getCallbackTokenAsync method which include the SMTP address directly. And to validate the callback token, we can verify whether we can get the item info with EWS.
For example, there is an ‘parentItemId’ in the callback token. It is same that retrieve the claims from the callback token as id token since there are is JWT token. You can refer to here for more detail.
Then we can use the code below to get the item information from EWS:
public bool Post([FromBody]EWSRequest request)
{
ExchangeService service = new ExchangeService();
service.Credentials = new OAuthCredentials(request.token);
service.Url = new Uri(request.ewsURL);
//get item id from callback token
var itemId = "";
Item item = Item.Bind(service, itemId);
var subject = item.Subject;
return subject.Length>0;
}
public class EWSRequest
{
public string token;
public string ewsURL;
}
JavarScript :
Office.context.mailbox.getCallbackTokenAsync(getCallbackTokenCallback)
function getCallbackTokenCallback(asyncResult) {
var _token = asyncResult.value;
var _ewsURL = Office.context.mailbox.ewsUrl;
var serviceEndpoint = "https://localhost:44300/API/token/"
var postData={ token: _token, ewsURL: _ewsURL }
$.ajax({
url: serviceEndpoint,
type: "post",
contentType: "application/json",
data: JSON.stringify(postData),
success: function (result) {
var ret = result;
}
})
}

LibGit2Sharp: Fetching fails with "Too many redirects or authentication replays"

Here's the code I'm using to fetch:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
var fetchOpts = new FetchOptions {Credentials = creds};
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
but it fails during fetch with the following exception:
LibGit2Sharp.LibGit2SharpException: Too many redirects or authentication replays
Result StackTrace:
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
at LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteSafeHandle remote, Signature signature, String logMessage)
at LibGit2Sharp.Network.DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options, Signature signature, String logMessage)
at LibGit2Sharp.Network.Fetch(Remote remote, FetchOptions options, Signature signature, String logMessage)
I have verified that the config file has the required remote name and that git fetch works from the command line. I found that the exception originates from libgit2\src\transport\winhttp.c but I couldn't come up with a workaround/solution.
I tried #Carlos' suggestion in the following way:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
CredentialsHandler credHandler = (_url, _user, _cred) => creds;
var fetchOpts = new FetchOptions { CredentialsProvider = credHandler };
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
I could fetch from public repos on github as well as from password protected private repos on bitbucket; however, I couldn't do the same for the repositories hosted over LAN at work. Turns out they were configured in a way which does not accept UsernamePasswordCredentials provided by libgit2sharp. The following modification allowed me to fetch from repositories over LAN:
CredentialsHandler credHandler = (_url, _user, _cred) => new DefaultCredentials();
(I'm trying to find out what is the exact difference between the two; if I get further insight into it, I'll update the answer.)
The shim that should make the Credentials option work is currently buggy (and is deprecated anyway), pass a CredentialsProvider instead as a callback.
This seems to be a very common error message.
We were getting it on pushes to GitHub, because credentials were disabled for security:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
We've solved it by enabling SAML SSO and doing the push outside the C# code, but perhaps using SSH keys somehow with the library or personal access tokens fixes the problem too.

How to do Active Directory authentication in Razor (cshtml)

I am doing a simple website with Razor. Currently, I have database-based authentication that works, as follows:
In _AppStart.chtml:
WebSecurity.InitializeDatabaseConnection("db_connection",
"users", "id", "username", true);
In login.cshtml page:
username = Request["username"];
password = Request["password"];
if (WebSecurity.Login(username, password, true))
{
Response.Redirect("/admin");
}
else
{
errorMessage = "Login was not successful.";
}
In protected CSHTML pages, I have the following at the top of a page:
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("/login.cshtml");
}
Everything is pretty simple and works well. Now I would like to add authentication with AD. I don't know how to do it.
I came from the Java world with many years of experience. For this simple website, I do not need MVC architecture. I need simple things similar to the above (if possible). I need to do authentication just within the login.cshtml file. I googled a lot and am unable to find a tutorial (so that I can copy and paste) for what I need.
Any pointers or help is really appreciated!
Thanks and Regards
Update: This application sits on the internal network.
Update 2: Here is the code I have after successfully implemented X3074861X's code
if (IsPost)
{
username = Request["username"];
password = Request["password"];
var domain = "domain";
var host = "host";
var port = "389";
LdapConnection ldapConnection = new LdapConnection(host + ":" + port);
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// this is where the authentication occurs
ldapConnection.Bind(networkCredential);
//check local database to make sure the user is one of we allowed
if (WebSecurity.Login(username, "fixed-password, just to check whether someone is on the list of allowed people", true))
{
Response.Redirect("/admin");
}
else
{
errorMessage = "Login was not successful.";
}
}
}
catch (LdapException exception)
{
//Authentication failed, exception will dictate why
errorMessage = "Login was not successful.";
}
Some explanation. I dont have control over the AD and so I can only authenticate users against it. I still have a little local database that indicates who can access the app. Everyone with access to the app has the same rights.
Thanks and credit goes to X3074861X.
Since this is an internal application, and you're looking for something simple, I would consider writing a single class to do the Active Directory authentication. You're going to need a couple things though, in order for this to work :
A reference to System.DirectoryServices.Protocols in your project.
The IP or DNS name of your Active Directory server. We'll call it host in the code below.
The port it's running on (LDAPS will be port 636, basic LDAP will be port 389). We'll call it port in the code below.
The Domain to which your users belong. We'll call it domain in the code below.
Now that you have that, you can wire this up to check the credentials from the request against your AD instance. I would try something like this :
// the username and password to authenticate
username = Request["username"];
password = Request["password"];
// define your connection
LdapConnection ldapConnection = new LdapConnection("host:port");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
Also, in the same way you'd communicate an authorization issue before, the ldapException can tell you why the call failed. If you want to display custom messaging, I would check the LdapException.ErrorCode property, and maybe create a case statement of return messages based on the error codes.
Or, you could just output LdapException.Message directly to the page - either way, that will at least dictate to the user why their login didn't work.

ArgumentException: Precondition failed.: !string.IsNullOrEmpty(authorization.RefreshToken) with Service Account for Google Admin SDK Directory access

I'm trying to access the Google Directory using a Service Account. I've fiddled with the DriveService example to get this code:
public static void Main(string[] args)
{
var service = BuildDirectoryService();
var results = service.Orgunits.List(customerID).Execute();
Console.WriteLine("OrgUnits");
foreach (var orgUnit in results.OrganizationUnits)
{
Console.WriteLine(orgUnit.Name);
}
Console.ReadKey();
}
static DirectoryService BuildDirectoryService()
{
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DirectoryService.Scopes.AdminDirectoryOrgunit.GetStringValue()
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "TestProject1",
});
}
When I run it, I get
ArgumentException: Precondition failed.: !string.IsNullOrEmpty(authorization.RefreshToken)
I'm going round in circles in the Google documentation. The only stuff I can find about RefreshTokens seems to be for when an individual is authorizing the app and the app may need to work offline. Can anyone help out or point me in the direction of the documentation that will, please.
Service Account authorization actually do not return Refresh Token - so this error makes sense. Do you know where this is coming from?
I am not too familiar with the .NET client library but having the full error trace would help.
As a longshot - The error might be a bad error -
Can you confirm that you've enabled the Admin SDK in the APIs console for this project
Can you confirm that you whitelisted that Client ID for the service account in the domain you are testing with (along with the Admin SDK scopes)
The above code will work if you replace the provider block with:
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DirectoryService.Scopes.AdminDirectoryOrgunit.GetStringValue(),
ServiceAccountUser = SERVICE_ACCOUNT_USER //"my.admin.account#my.domain.com"
};
I had seen this in another post and tried it with my standard user account and it didn't work. Then I read something that suggested everything had to be done with an admin account. So, I created a whole new project, using my admin account, including creating a new service account, and authorising it. When I tried it, it worked. So, then I put the old service account details back in but left the admin account in. That worked, too.

Refresh Token with Google API Java Client Library

I'm using the Google API Java Client http://code.google.com/p/google-api-java-client/ and am able to get the access token successfully for Android.
// Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, CalendarScopes.CALENDAR);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
As I'd like my web server to make offline API calls, I need a refresh token. I have been searching extensively and have not yet figured out how to do so.
Ideally, I'd prefer to use the Google API Java Client over the WebView to grab the refresh token (no need to enter a username or password).
Any help would be appreciated!
You can also do this by creating a refresh token configured to a OAuth 2.0 Client Id.
Go to https://console.developers.google.com/apis/credentials
Click 'Create Credential'.
Click 'OAuth client Id'.
Select 'Web application' > Give a name.
Add https://developers.google.com/oauthplayground to 'Authorized redirect URIs'.
Click Create.
You will need the ClientId and the Secret for next steps.
Then go to https://developers.google.com/oauthplayground/
Click 'AOuth 2.0 Configuration' on right upper corner.
Check 'Use your own OAuth credentials'.
Update 'OAuth Client ID' and 'OAuth Client secret' with client id and secret of above created OAuth 2.0 credential.
In Step 1 on left corner, Select all the necessary scopes.(Please note that unmatching scopes in request will return 'invalid_scopes'.)
Click 'Authorize APIs'. This will redirect you to a consent page to allow permissions.
In Step 2, click 'Exchange authorization code for tokens'
You will get an Access Token with a Refresh Token. We will need this Refresh Token for the next step.
You can use this access token to authenticate to services you specified in scopes.
Access Tokens are short lived and Refresh tokens expire after 24 hours unless it is not bound to a OAuth 2.0 client (We just made our refresh token to last until it is revoked by the user or expires due to 6 months inactivity).
You need to refresh the Access Token before it expires. Check out following example to see how.
public String getNewToken(String refreshToken, String clientId, String clientSecret) throws IOException {
ArrayList<String> scopes = new ArrayList<>();
scopes.add(CalendarScopes.CALENDAR);
TokenResponse tokenResponse = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
refreshToken, clientId, clientSecret).setScopes(scopes).setGrantType("refresh_token").execute();
return tokenResponse.getAccessToken();
}
clientId and clientSecret in above example refers to OAuth 2.0 client credentials.
You can create a 'GoogleCredential' with that like this
public Credential getCredentials() throws GeneralSecurityException, IOException, FileNotFoundException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
// Load client secrets.
String CREDENTIALS_FILE_PATH = "/credentials.json"; //OAuth 2.0 clinet credentials json
InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
String clientId = clientSecrets.getDetails().getClientId();
String clientSecret = clientSecrets.getDetails().getClientSecret();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(clientId, clientSecret)
.build();
String refreshToken = "<REFRESH-TOKEN>"; //Find a secure way to store and load refresh token
credential.setAccessToken(getNewToken(refreshToken, clientId, clientSecret));
credential.setRefreshToken(refreshToken);
return credential;
}
You need to set the following when you initiate the authorization flow :
approval prompt = force
access type = offline
With these params set, google will return a refresh token and the library will deal with refreshes. This works for me :
new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(),
Arrays.asList(SCOPES)).setCredentialStore(new OAuth2CredentialStore()).setAccessType("offline")
.setApprovalPrompt("force").build();