I tried to get Active Directory username in orchard module, but instead I get IIS APPPOOL\orchardcms
The code I'm using in the controller working fine in the ORchard source code but when I deploy it in the IIS server it resulting and IIS username instead of active directory username.
In the controller
public ActionResult Index()
{
ViewBag.ADUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return View();
}
Inthe View
Welcome, #ViewBag.ADUserName
In views you can simply write
#User.Identity.Name
to get the name of the current user.
Related
I have created a API app and deployed it to Azure. The app uses Active directory authentication.
I get the following error
AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: 00000000-0000-4f27-0000-00000000.
Steps so far
Enabled Active directory authentication
Set CORS to *
Set Reply URL to same address https://myapp.azurewebsites.net/
I have added the following settings in the web config
config
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}"></add>
<add key="ida:PostLogoutRedirectUri" value="https://myapp.azurewebsites.net/"></add>
The code for the api is as follows
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK,
Type = typeof(IEnumerable<Contact>))]
public async Task<IEnumerable<Contact>> Get()
{
return await GetContacts();
}
Get a Fiddler trace of what goes through your browser when you try to authenticate to the app. There should be a request to AAD asking for authentication, which will also include a reply url. Make sure it is the same as the one your app is configured with in AAD.
Have you set below key and value on web.config.
key="ida:RedirectUri" value="https://myapp.azurewebsites.net/"
Had the same error, the solution was:
Go to the Azure portal: https://portal.azure.com sign in and click on the Azure Active Directory icon on the left. Then click on the ‘App registrations’ icon in the middle pane. In the search box enter the application from the error message and choose ‘All apps’ from the dropdown:
Click on your application, then the Settings icon, select the ‘Reply URLs’ from the list.
Copy One of reply URL and add it in your application as an https port.
You can do that from properties of the project or just add in lounchsetting.json files sslPort value
On the AAD App Registration, append the AAD auth callback to your Reply URI value. Originally I had mine set to something like:
https://my-app.azurewebsites.net
I then updated this to:
https://my-app.azurewebsites.net/.auth/login/aad/callback
After that, the error was cleared & I was able to call my API endpoints.
I had this same issue when following the MS tutorial Call the Microsoft Graph API from a Windows Desktop app. There was no place in my code where I was supplying a redirect url, except on this line
.WithDefaultRedirectUri();
Which upon hovering over it I could see was https://login.microsoftonline.com/common/oauth2/nativeclient, which was a redirect uri that was present on my app on Azure. This was all quite confusing and I did not find an answer anywhere online. After about 3 hours of searching for answers and playing around with many possibilities in the code I found this comment in one of the files I downloaded:
// Requires redirect URI "ms-appx-web://microsoft.aad.brokerplugin/{client_id}" in app registration
So I went to https://ms.portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Authentication/appId/171axxxx-xxxx-xxxx-xxxx-xxxxxxxxafff/isMSAApp/ and under Authentication >Redirect URIs I added the redirect URI ms-appx-web://microsoft.aad.brokerplugin/171axxxx-xxxx-xxxx-xxxx-xxxxxxxxafff.
Next I modified my code like this:
public partial class App : Application
{
// Below are the clientId (Application Id) of your app registration and the tenant information.
// You have to replace:
// - the content of ClientID with the Application Id for your app registration
// - The content of Tenant by the information about the accounts allowed to sign-in in your application:
// - For Work or School account in your org, use your tenant ID, or domain
// - for any Work or School accounts, use organizations
// - for any Work or School accounts, or Microsoft personal account, use common
// - for Microsoft Personal account, use consumers
private static string ClientId = "171axxxx-xxxx-xxxx-xxxx-xxxxxxxxafff";
// Note: Tenant is important for the quickstart.
private static string Tenant = "72f9xxxx-xxxx-xxxx-xxxx-xxxxxxxxdb47"; //also works with "common"
private static string Instance = "https://login.microsoftonline.com/";
private static IPublicClientApplication _clientApp;
static App()
{
CreateApplication(true);
}
public static void CreateApplication(bool useWam)
{
//initialize MSAL
var builder = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority($"{Instance}{Tenant}")
.WithDefaultRedirectUri();
if (useWam)
{
builder.WithExperimentalFeatures();
builder.WithBroker(true); // Requires redirect URI "ms-appx-web://microsoft.aad.brokerplugin/{client_id}" in app registration
}
_clientApp = builder.Build();
TokenCacheHelper.EnableSerialization(_clientApp.UserTokenCache);
}
public static IPublicClientApplication PublicClientApp { get { return _clientApp; } }
}
I don't know why Azure didn't just add this in with the other redirects since they knew it would be needed, or at least include this step in the instructions, but hopefully this will be helpful to someone else experiencing this error.
Hi I am developing web application. I am using Azure active directory for login process. I am working on admin consent. I am able to redirect to admin consent and give the consent. In admin consent page,whenever i clicked on the cancel button in admin consent I am redirecting to error page.
Below is the url I am redirecting when clicked on the admin consent page.
https://mywebsite.net/adminconsent?error=access_denied&error_description=AADSTS65004%3a+The+resource+owner+or+authorization+server+denied+the+request.%0d%0aTrace+ID%3a+7798f669-f82d-4b55-8c9b-1259142e1900%0d%0aCorrelation+ID%3a+82764c15-3e79-4905-840b-952af3dfe6fc%0d%0aTimestamp%3a+2018-09-07+13%3a30%3a42Z
Can someone help me to identify the root cause of the issue? Any help would be appreciated. Thank you.
You're getting the relevant error code back from Azure AD - 65004, telling you the root cause, that Admin has declined to consent. Description is visible in the URL and if you can confirm the meaning of error code by looking it up here -
Sign-in activity report error codes in the Azure Active Directory portal
65004 User declined to consent to access the app. Have the user retry
the sign-in and consent to the app
Update about displaying a meaningful error page
You haven't mentioned what is it that you're using to write your web application. In any case, I tried out a quick ASP.NET MVC web application with similar setup and I clearly get back the response in query string parameters. All you need to do is, read the query string from the URL (I have HttpRequest.QueryString collection in my sample) and check for error/error_description.
Here is a quick sample code on doing that in the MVC controller..
public class AdminConsentController : Controller
{
// GET: AdminConsent
public ActionResult Index()
{
if (Request.QueryString.AllKeys.Contains("error")
&& Request.QueryString.AllKeys.Contains("error_description"))
{
string errorDescription = Request.QueryString["error_description"];
if(errorDescription.Contains("AADSTS65005"))
{
//Do something good about it..
}
}
//if no errors, simply return the view
return View();
}
Since you mention Angular 5.. here's a quick sample for that.
Take a look at this SO post for multiple options
ngOnInit() {
this.param1 = this.route.snapshot.paramMap.get('param1');
this.param2 = this.route.snapshot.paramMap.get('param2');
}
And if you don't want to use anything fancy, plain old window.location should always work from client side. May not be the recommended way though.
window.location.href
Following along with the Xamarin native sample, the sample itself seems to work fine on ios, but when I put in my own credentials, after entering user name and password I an popup that says "Safari cannot open the page because the address is invalid". This is my main problem, if anybody can advise that would be very grateful.
The bigger issue though is I don't understand what is actually going on in the code. I'm not looking for a redirect after authentication anyway. I'm just trying to get a token back to my app's code, so I would like to dismiss the webform and return control to my code. But instead I am stuck with the popup. (This all works fine and as expected in the sample, but when I put in my own credentials, as best as I can figure them out based on the notes in the sample, I get this error.)
I'm thinking it must have to do something with the scopes or redirect settings on the Tenant, but its all very opaque on the page and in the documentation what any of this means E.g. what is a "scope?" in the first place, and why is the value as the scope argument in thhe sample a url?
From what I can tell, what I want the scope to be is "OpenId" since I am using local authentication, but if you set "scopes" to the { "OpenId" } you get an error saying those scopes are already included. But if you leave it blank, you also get an error saying scopes are required. So what up with that?
With respect to tenant setting page, if I am only building something to service logins on my app, why do I need to answer "yes" to the question "Include web app/web api?". Why is the reply url set to non-existent value "https://myapi"? Why is the App ID Uri set to "https://[applicationName]/onmicrosoft.com/demoapi? and what is its purpose?
In the "Native Client" section, the registration provides pre-populated fields "Redirect Uri" and "custom redirect uri". The Redirect URI looks like "urn:ietf:wg:oauth:2.0:oob". What is that? the pop up says it's a
"Unique identifier which B2C will redirect the user agent in an
Oath2.0 response"
but it doesnt look like there are enough letters here to possibly be unique ID.
The there is a thing called "the "custom" redirect uri, which I guess is different than the plain old "Redirect URI" and that one looks like
msal3b4c7038-694a-42d6-bab0-43d5b1f86106://auth
So why is one "custom" and why is the other apprarently not custom?
Sorry for all the questions but I can't find good documentation explaining any of this. Much appreciated, and if anyone from Azure is listening, maybe they could point to some Xamarin/Azure documentation that would help me understand this.
Many thanks!
PS Maybe this post has too many questions, and not sure if I am supposed to split these up into separate questions. If so, please let me know. My main question is the first one.
Relevant Code below:
public static string Tenant = "crowdwisdom.onmicrosoft.com";
public static string ClientID = "3b4c7038-694a-44c6-bab0-43d5b1f86106";
public static string PolicySignUpSignIn = "B2C_1_susi";
public static string PolicyEditProfile = "B2C_1_edit_profile";
public static string PolicyResetPassword = "B2C_1_reset";
public static string[] Scopes = { "https://crowdwisdom.onmicrosoft.com/demoapi/demo.read" };
public static string ApiEndpoint = "https://crowdwisdom.azurewebsites.net";
public static string AuthorityBase = $"https://login.microsoftonline.com/tfp/{Tenant}/";
public static string Authority = $"{AuthorityBase}{PolicySignUpSignIn}";
public static string AuthorityEditProfile = $"{AuthorityBase}{PolicyEditProfile}";
public static string AuthorityPasswordReset = $"{AuthorityBase}{PolicyResetPassword}";
public static UIParent UiParent = null;
...
async void OnSignInSignOut(object sender, EventArgs e)
{
try
{
if (btnSignInSignOut.Text == "Sign in")
{
AuthenticationResult ar = await App.PCA.AcquireTokenAsync(App.Scopes, GetUserByPolicy(App.PCA.Users, App.PolicySignUpSignIn), App.UiParent);
UpdateUserInfo(ar);
UpdateSignInState(true);
}
else
{
foreach (var user in App.PCA.Users)
{
App.PCA.Remove(user);
}
UpdateSignInState(false);
}
}
catch(Exception ex)
{
// Checking the exception message
// should ONLY be done for B2C
// reset and not any other error.
if (ex.Message.Contains("AADB2C90118"))
OnPasswordReset();
// Alert if any exception excludig user cancelling sign-in dialog
else if (((ex as MsalException)?.ErrorCode != "authentication_canceled"))
await DisplayAlert($"Exception:", ex.ToString(), "Dismiss");
}
}
Here's the Azure B2C tenant settings:
See my other answer above or below that answers the question regarding redirect URI's.
Scopes:
Scopes are mostly necessary when you're calling an API. Think of them like permissions. For example, you could have a "tasks list" api that stores your tasks for the day. Suppose you want your app to be able to "read" from the API. So you call Azure AD B2C, and request an access token that gives you the ability to "read" from the API. You would do this by inserting "read" as one of the scopes in your request.
The problem is, any API can have a read scope, so to distinguish which API you are referring to, you use the App ID URI. So in Azure AD B2C, you set the App ID URI as "https://tenantName.onmicrosoft.com/tasksList". Then when you're making the request, you specify the scope as "https://tenantName.onmicrosoft.com/tasksList/read" (notice that 'read' was added to the end of that "URL")
I'll break down my answer into two posts since there are two different sets of questions here.
Redirect URI's ( how to return to your app )
Leaving the browser and returning to your app is mostly done using the redirect uri. The MSALxxxxxx://oauth is the redirect uri path that you (according to your screenshot) have registered with B2C. That looks good. When you're making the call to Azure AD B2C, you need to make sure the redirect URI is set to that value. When Azure AD B2C generates a token, it will send it forward to that redirect URI.
Now, the app needs to receive that token. This is done by listening to a uri scheme, which is everything before the colon. In this case, the URI scheme is MSALxxxxxx. To configure your xamarin app to listen to that URI scheme, follow step 6 in this sample. That steps helps you configure the return URI for each kind of platform. Now, whenever the browser detects a redirect to MSALxxxx, it will send the message forward to your app. In this case, you will receive a B2C token in your message.
By the way, "urn:ietf:wg:oauth:2.0:oob" is just a default redirect URI that we provide. We recommend you only use it for testing purposes, and that you create a unique redirect URI scheme for your app.
As neither of the answers helped me solved this I'll put my answer here as the libraries have been updated since this post.
The new way to add a redirect URI to the Azure AD B2C Application is like so:
But I can't find instructions on how to configure the app correctly to make this work. So I had to configure the redirect in the old way like so:
This stopped the error in Safari which I worked out from adding logging to the Microsoft.Identity library, copying the URL it was trying to load from the logs, and pasting it into Safari. This showed that the error from Azure was a missing redirect.
I hope this helps someone else and if you know why the new way is not working please post it here too.
I've got a sharepoint site and a custom aspx portal, both under Windows Authentication.
With the same machine, it happens that my sharepoint site returning me my current login, while my custom aspx returning me my domain admin account instead.
Is there anyway that I could ensure both logins are the same? Otherwise, is there anyway to consume SPUserProfileService from a custom aspx portal?
Mainly, I need to have the custom aspx portal to get sharepoint logon id. Nevertheless, i could still trigger AccessDenied.aspx in sharepoint to prompt for logins.
When you say "Custom ASPX Portal", is it still hosted on the SharePoint Site?
In that case, how do you get the user? You can use SPContext.Current.Web.CurrentUser to get the user.
It seems that you are connecting from your custom aspx to SharePoint using your Domain Admin Account.
Could you please describe more about your custom aspx portal and the way you are reading the username?
However, you can check my article (Even though it is for FBA users, you may find the code snippet useful):
Possible ways to get logged in User Name & Handling Changes in FBA Users' Names if Membership Provider Name Changed
public string GetFlatUserName()
{
//First, be sure that the user is not anonymous user:
if (SPContext.Current == null || SPContext.Current.Web.CurrentUser == null)
return "Anonymous";
//Second, parse it:
else
{
string flatUserName = this.Page.User.Identity.Name;
if (flatUserName.Contains("\\"))
{
flatUserName = flatUserName.Substring(flatUserName.IndexOf("\\") + 1);
}
else if (flatUserName.Contains("|"))
{
flatUserName = flatUserName.Substring(flatUserName.IndexOf("|") + 1);
}
return flatUserName;
}
}
I'm trying to run a console application that uses the SharePoint Object Model.
I'm getting the error Cannot open database "dbname" requested by the login. The login failed. Login failed for user 'DOMAIN\userid'.
Some place I have read that the user must have permission to the Content DB.
I can not find an article that explains what permissions to setup. I need this as ammunition to go to my Sys Admin guy to get the permission setup.
Where is there an article that explains that? I have searched google but with no luck.
RunWithElevatedPrivileges doesn't help because it just changes the thread user to the process identity - in a console application, this has no effect because they're the same. The "elevation" in an impersonated web context works because the process identity is the application pool account, which has db_owner on its content database.
If I ask that the account I'm using be given Full Control, under the Policies for Web Application, should that work?
Not according to Ishai Sagi: Object model code and stsadm fail with "Access Denied". In short, it seems db_owner permissions on the content database are required for a user to run object model code (including STSADM) without a web context.
Are you running the console application on the server itself? I assume so.
In this case it is likely to be a permissions issue with the account you are using (RDP?) on the server. The database error side of things can be misleading as you will need to be permissioned within SharePoint itself, which will then give permissions to the database.
I would get your sys admins to create a service account for you to use that can be granted the correct rights. (site collection administrator is often needed, but it depends on the code inside the console app. most do assume site collection admin rights though). you may get more mileage from looking at the application instructions (or if it is your own code just go for site collection admin)
Running a console app is a bit of a major though, so you may have better luck if you give the sysadmins the application to run and instructions... though I doubt you are running this on the prod box.
your user propably don't have permissions to access those lists or webs. You can run your code with elevated privilegies, but it can sometimes give you unexpected results.
Example of how elevated privilegies is used can be found here
Or you can set user unser who's account console app runs as site collection administrator.
Your code updated to run with elevated privilegies can look like this:
private static void DisplayAllLists(string site, string webToOpen)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using ( SPSite siteCollection = new SPSite(site) )
{
try
{
using (SPWeb web = siteCollection.OpenWeb(webToOpen))
{
SPListCollection lists = web.Lists;
foreach (SPList list in lists)
{
Console.WriteLine(string.Format("List Title: {0}", list.Title));
}
}
}
}
finally
{
siteCollection.RootWeb.Dispose();
Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: "+ex.Message);
}
}
Note: This code was written from top of my head, so maybe something is missing..you will have to try it