We couldn't sign you in. Please try again - azure-active-directory

I'm getting the error We couldn't sign you in. Please try again. when I try to login to my custom web app that uses Azure AD. The client secret expired so I figured I could just create a new one and replace it to see if that fixes it. However my current app doesn't seem to have a client secret.
I used a lot of boilerplate code to set this up originally so I don't know what's going on with this to be honest. Below is my Startup.cs file where I pull the client ID and other stuff from the web.config file. Notice a lack of client secret.
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string replyUrl = ConfigurationManager.AppSettings["ida:ReplyUrl"];
private static string authority = aadInstance + tenantId;
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = replyUrl
});
}
private static string EnsureTrailingSlash(string value)
{
if (value == null)
value = string.Empty;
if (!value.EndsWith("/", StringComparison.Ordinal))
return value + "/";
return value;
}
Can someone point me in the right direction? Or it may be something completely different. After I login it does a bunch of redirects and ends up with the error mentioned above.

Turns out I was accessing the original URL on http and not https and that was causing an issue.

Related

Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

Spring data with LDAP (Active Directory) returns WILL NOT PERFORM in any writing operation

I'm currently trying to implement an simple CRUD integrated with Active Directory via LDAP, using Spring Data, for managing my internal users.
The problem is, while the reading works as expected, any writing on AD (creating or editing a user, for example) results in a generic error message, shown below:
[LDAP: error code 53 - 0000209A: SvcErr: DSID-031A107A, problem 5003 (WILL_NOT_PERFORM), data 0\n\u0000]; remaining name 'DC=company, DC=com'
The ldap connection is being made using LDAPS with an admin user. I can even work with the same credentials without any issues in a simple nodejs test application. So I'm probably making some mistake with Spring Data.
The relevant source code is attached below.
Entity class:
// Person.java (Entity model)
#Data
#Entry(
base = "ou=Employees,dc=company,dc=com",
objectClasses = {"person", "top"}
)
public class Person {
#Id
private Name dn;
#Attribute(name = "cn")
private String commonName;
#Attribute(name = "sAMAccountName")
private String accountName;
#Attribute(name = "userPrincipalName")
private String username;
#Attribute(name = "mail")
private String mail;
#Attribute(name = "userPassword")
private String password;
#Attribute(name = "description")
private String desc;
#Attribute(name = "memberOf")
private List<String> groups;
#Attribute(name = "company")
private String company;
#Attribute(name = "objectClass")
private List<String> objectClasses;
#Attribute(name = "objectCategory")
private String objectCategory;
}
Repository class:
// PersonRepository.java
#Repository
public interface PersonRepository extends LdapRepository<Person> {
Person findByMailIgnoreCase(String mail);
}
Service class:
#Service
public class UserService {
#Autowired
private PersonRepository personRepository;
/**
* Save the user at AD.
*
* #param username the user login name
* #param name the user name and surename
* #param companyExtName the company external name
* #param email the user email
* #param description the user description
* #return the newly created user
*/
public Person createPerson(String username, String name, String companyExtName,
String email, String description) {
final Person user = new Person();
user.setAccountName(username);
user.setCommonName(name);
user.setCompany(companyExtName);
user.setMail(email);
user.setUsername(email);
String tempPass = RandomStringUtils.randomAscii(10);
user.setPassword(digestSHA(tempPass));
user.setDn(LdapNameBuilder.newInstance("DC=company, DC=com")
.build());
List<String> objClasses = new ArrayList<>();
objClasses.add("person");
objClasses.add("top");
user.setObjectClasses(objClasses);
user.setObjectCategory("CN=Person,CN=Schema,CN=Configuration,DC=company,DC=com");
List<String> groups = new ArrayList<>();
groups.add("CN=Administrators,CN=Builtin,DC=company,DC=com");
user.setGroups(groups);
if (description != null && !description.isEmpty()) {
user.setDesc(description);
}
return personRepository.save(user);
}
/**
* Encodes the user password as it is used at Active Directory
*
* #param plain the plain text password
* #return the password hash
*/
private static String digestSHA(String plain) {
try {
MessageDigest digester = MessageDigest.getInstance("SHA-256");
digester.update(plain.getBytes());
return String.format("{SHA}%s", Base64.getEncoder().encodeToString(digester.digest()));
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
The exception is thrown when I call personRepository.save(user);
As a addtional information, I've already tried a few variations of the code attached -- tried to remove almost all user data beforing saving it, different password encodings and hashing -- but the result is always the same.
Any help on this will be greatly appreciated.
Thanks!
EDIT:
Investigation indicates that the cause is probably something related with the way I'm sending my user DN.
Anyway, I'm still wrestling with this issue.
I was able to create/edit my Active Directory users with a workaround.
In my UserService, instead of using the Spring Data Ldap repository, I've used the LdapTemplate methods, like shown below.
// UserService.java
public void createPerson() {
Name userDn = LdapNameBuilder
.newInstance()
.add("ou", ou)
.add("cn", accountName)
.build();
DirContextAdapter context = new DirContextAdapter(userDn);
context.setAttributeValue("cn", accountName);
context.setAttributeValue("sn", accountName);
context.setAttributeValue("userPassword", digestSHA(password));
context.setAttributeValue("company", company);
context.setAttributeValue("description", desc);
context.setAttributeValue("mail", mail);
context.setAttributeValue("sAMAccountName", accountName);
context.setAttributeValue("userPrincipalName", username);
context.setAttributeValue("objectCategory", objectCategory);
context.setAttributeValues("objectClass", objectClasses.toArray());
DirContextAdapter context = user.getLdapContext("Users");
ldapTemplate.bind(context);
}
Since I used the same values for user creation with both Spring Data and LdapTemplate, my original issue is probably related to some treatment Spring does before sending the data to my Active Directory server.
Since the method above is currently working for me, I'll follow with it. When I have some spare time I'll go back to this to find out what I was doing wrong with Spring.
For future use, I believe it is related to memberOf attribute. This attribute must be set after the user is created, but it seems that Spring Data is filling this property with an empty string even if I set the attribute to null when creating the user.
Lots of articles says that it is because of a lack of SSL connection to a LDAP server.
Here are some links:
stackoverflow.com/questions/17290539
stackoverflow.com/questions/6797955
forum.spring.io/forum/spring-projects/data/ldap
community.oracle.com/thread/2177638

"scope not allowed" on localhost only

I'm getting started with Google App Engine with Java, and using Google Cloud Endpoints with OAuth 2.0. I have one simple endpoint working correctly, but only when deployed. When I run it on my local machine I get this error:
Mar 10, 2014 4:38:54 PM com.google.api.server.spi.WebApisUserService getCurrentUser
INFO: getCurrentUser: AccessToken; scope not allowed
Here is my endpoint code:
#Api(
name = "sd",
version = "v1",
scopes = { Constants.EMAIL_SCOPE },
clientIds = { Constants.WEB_CLIENT_ID, Constants.API_EXPLORER_CLIENT_ID })
public class Feeds {
public Feed sample(User user) {
if (user == null) {
return new Feed("Public Feed.");
} else {
return new Feed("Feed for " + user.getEmail());
}
}
}
...
public class Constants {
public static final String WEB_CLIENT_ID = "<snip>.apps.googleusercontent.com";
public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
public static final String API_EXPLORER_CLIENT_ID = com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID;
}
As I said, when I deploy this and access it via the API Explorer in all works perfectly. When I have the OAuth toggle on, it returns Feed for <my email address>, and when I turn it off it returns Public Feed.
However, when run against my local machine it always returns Public Feed. When the OAuth toggle is on, it prints the error pasted at the top of this post to the server's console. I am accessing the two api explorers with the urls https://<app_id>.appspot.com/_ah/api/explorer and http://localhost:8888/_ah/api/explorer.
Can anyone help?

Google Plus DomainsAPI wide-domain autorization

Good morning I'm trying to integrate the Google+ Domains API with my company domain but I'm facing some problems.
I'm trying the java approach following the quick start for java but after implement the code the response from the google server is :
Authenticate the domain for hugo.catarino#outsystems.com
Inserting activity
10/Set/2013 17:08:49 com.google.api.client.googleapis.services.AbstractGoogleClient <init>
WARNING: Application name is not set. Call Builder#setApplicationName.
Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException:400 Bad Request
{
"error" : "access_denied"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.google.plus.samples.quickstart.domains.DomainDelegation.main(DomainDelegation.java:160)
here is used authentication method and my variables:
private static final String SERVICE_ACCOUNT_EMAIL = "638852846577#developer.gserviceaccount.com";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH =
"src/com/google/plus/samples/quickstart/domains/05cab8e819cbd0a747b180c1f22fc93dba916b7b-privatekey.p12";
private static final String USER_EMAIL = "hugo.catarino#outsystems.com";
private static Plus authenticate() throws GeneralSecurityException, IOException {
System.out.println(String.format("Authenticate the domain for %s", USER_EMAIL));
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// Setting the sub field with USER_EMAIL allows you to make API calls using the special keyword
// 'me' in place of a user id for that user.
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPE)
.setServiceAccountUser(USER_EMAIL)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)).build();
// Create and return the Plus service object
Plus service = new Plus.Builder(httpTransport, jsonFactory, credential).build();
return service;
}
My main class has the following code like in the sample:
Plus service = authenticate();
String userId = "me";
String msg = "Happy Monday! #caseofthemondays";
System.out.println("Inserting activity");
// Create the audience of the post
PlusAclentryResource res = new PlusAclentryResource();
// Share to the domain
res.setType("domain");
List<PlusAclentryResource> aclEntries = new ArrayList<PlusAclentryResource>();
aclEntries.add(res);
Acl acl = new Acl();
acl.setItems(aclEntries);
// Required, this does the domain restriction
acl.setDomainRestricted(true);
Activity activity = new Activity()
.setObject(new Activity.PlusObject().setOriginalContent(msg))
.setAccess(acl);
activity = service.activities().insert(userId, activity).execute();
System.out.println(activity);
In domain cPanel the company defined for me the next scopes:
https://www.googleapis.com/auth/plus.circles.read
https://www.googleapis.com/auth/plus.circles.write
https://www.googleapis.com/auth/plus.me
https://www.googleapis.com/auth/plus.media.upload
https://www.googleapis.com/auth/plus.stream.read
https://www.googleapis.com/auth/plus.stream.write
My scope definition is:
private static final List<String> SCOPE = Arrays.asList(
"https://www.googleapis.com/auth/plus.circles.read",
"https://www.googleapis.com/auth/plus.circles.write",
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/plus.media.upload",
"https://www.googleapis.com/auth/plus.stream.read",
"https://www.googleapis.com/auth/plus.stream.write");
I'm a bit lost here , is there any way of debug this problem or know why is this access denied?
There are several things that you should check.
First, is the private key file that you downloaded from the Google APIs Console in the correct path with your code? This file is referenced by the following variable. This needs to tell the OAuth client library where to find the file.
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH =
"/path/to/<public_key_fingerprint>-privatekey.p12";
It is very important that you do not rename the file.
Second, does your scope list in your code match the list of scopes set in the Admin console?
The configuration in the Admin console for your Google Apps domain, and the scopes provided in the request must be identical. Try adjusting the SCOPE variable in your code to be:
private static final List<String> SCOPE = Arrays.asList(
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/plus.circles.read",
"https://www.googleapis.com/auth/plus.circles.write",
"https://www.googleapis.com/auth/plus.media.upload",
"https://www.googleapis.com/auth/plus.stream.read",
"https://www.googleapis.com/auth/plus.stream.write");
In general, it is best to only request the scopes that you will need, rather than all scopes available.
Third, make sure that the client ID you generated is the one listed on the Admin console entry that specifies the scopes permitted.

Exception occurred while reading mails from exchange server 2010 using imap

I am trying to read the mails from the exchange server 2010 , however sometimes the connection got established , but remaining times program gives below exception:
javax.mail.AuthenticationFailedException: LOGIN failed
The code is working fine with the exchange server 2007 . But from the time mailbox has been migrated to 2010, the program is behaving in this fashion only.
I have also tried with several options available on net, but nothing is working. I am using javamail-1.4.4 API version . Here is the piece of code through which I am just trying to connect to the mailbox .
public class ReadMail {
static Store store=null;
static String host="";
static String username="";
static String password="";
public static void main(String[] arg) throws Exception{
try{
Session session;
username = "username";
password = "password";
host = "hostname";
Properties props = System.getProperties();
props.setProperty("mail.smtp.auth","true");
session = Session.getInstance(props,
new ExchangeAuthenticator(username, password));
Store st = session.getStore("imaps");
st.connect(host,username, password);
System.out.println("Connected");
}
catch (Exception e){
e.printStackTrace(System.out);
}
}
}
public class ExchangeAuthenticator extends Authenticator {
String user;
String pw;
public ExchangeAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
I also face same problem in my code i set two properties in my code
disable plain test and enable NTLM
props.setProperty("mail.imap.auth.plain.disable","true");
props.setProperty("mail.imap.starttls.enable", "true");
now my code able to connect with exchange server
read it
https://forums.oracle.com/forums/thread.jspa?threadID=1587688
Perhaps the configuration of the server has changed and it's no longer accepting your credentials, or no longer supporting any of the login methods that JavaMail supports.
Turn on session debugging and examine the protocol trace. It should provide some clues as to why it's failing.
You might also want to upgrade to JavaMail 1.4.5, which has built-in support for NTLM authentication, which you might need.
Even though your credentials are OK, the new server might not accept your login method. For instance, the new server might not allow "Plain" authentication.
The debugging info should show which authentication methods are accepted.

Resources