I'm trying to get a user groups from the Azure AD.
I'm getting a token with these simple lines of code :
if (this.user == null)
user = await AuthenticationManager.DefaultManager.CurrentClient.LoginAsync(this, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);
if (user != null)
{
System.Diagnostics.Debug.WriteLine("Token = " + user.MobileServiceAuthenticationToken);
}
When I paste the token in the JWT debugger present on this website :
https://jwt.io/ I get some informations (stable_sid, sid, sub, idp,
ver, iss, aud, exp, nbf) but I can't seem to get the groups claim in them.
I added in Azured AD the required permissions to read groups for Microsoft graph and Azure active directory but it did not change anything in the tokens.
What am I missing to get the users groups ?
Thank you in advance.
EDIT : Commenter pointed that I forgot to mention that I modified the manifest to "groupMembershipClaims": "SecurityGroup", I also tried "All" but still no claims.
Okay, so there is actually no issue here.
What we are supposed to do to acces the user groups is use the authentication token in order to make calls to the Microsoft Graph API, which will then give us access to the groups and users in the tenant.
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api-quickstart
Related
I am using a Blazor application with Azure Active Directory authentication and guest users. When a user logs in, I want to use their authenticated identity as a key to lookup permissions and other attributes in my own database. Initially I used this code...
#using Microsoft.AspNetCore.Components.Authorization
#inject AuthenticationStateProvider AuthenticationStateProvider
#code {
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
//Don't do this: Name != email and may not even be constant
var email = user.Identity.Name;
var attributes = await myDatabase.FetchAttributesForUser(email);
//use attributes....
}
}
However, user.Identity.Name is not the email address of the user. As described in this old post, it is simply an identifier that the authentication provider supplies. For example, a user with an outlook address of first.last#outlook.com might be authenticated with a Name of live#first.last#outlook.com There's therefore no guarantee that the Name may be unique across providers or even across time for the same provider.
This stackoverflow question is identifying the same problem and the accepted answer is to use the SID but what is missing is an explanation of how I can retrieve the SID from the AuthenticationStateProvider that's been injected into my application. (There are no obvious fields or paths that lead to a SID.) Should I be injecting some other authentication object?
Also, if the recommendation is to use the SID, how can I obtain it for pre-provisioning? I.e. I invite "jo.bloggs#contoso.com" and want to set up attributes in my database before she first logs in. Is the "object id" shown in the portal actually the SID?
In Azure AD you can use either the oid or sub claim.
The oid claim contains the object id for the user in the Azure AD tenant they signed into.
It is thus unique across applications.
The sub claim is unique for that user in one application.
Both of them are immutable.
A .NET ClaimsPrincipal may contain the oid claim with a different name: http://schemas.microsoft.com/identity/claims/objectidentifier.
One source for these alternate names is the System.Security.Claims.ClaimTypes class.
Claims in id tokens: https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens#payload-claims
A general solution for obtaining the SID from the AuthenticationStateProvider with respect to the below in point asked in the original question.
This stackoverflow question is identifying the same problem and the accepted answer is to use the SID but what is missing is an explanation of how I can retrieve the SID from the AuthenticationStateProvider that's been injected into my application. (There are no obvious fields or paths that lead to a SID.) Should I be injecting some other authentication object?
If you notice, the AuthenticationState's User property returns the Identity property of type IIDentity which has the base functionalities for WindowsIdentity and other Identities as well. Hence converting the Identity into the WindowsIdentity becomes valid here. And after converting you can get the SID information of the user as below. The other information of the user can be obtained directly from the identity object.
var authenticationState = await authenticationStateTask;
WindowsIdentity identity = authenticationState.User.Identity as WindowsIdentity;
var SId = identity.User.Value;
Hope it helps.
I'm still learning identities with asp.net core. I'm doing a claims-based token authorization.
Most examples are about "Current" logged in user. In my case my RPC service is receiving a username & password of some user in the identity DB. I need to
verify that a user with such credentials exist
get all the claims of that user
so to verify if the user exists, I'm using this:
ApplicationUser applicationUser = await _userManager.FindByNameAsync(username);
bool exist = await _userManager.CheckPasswordAsync(applicationUser, password);
if (!exist)
{
// log and return
}
I don't know how to do the 2nd step properly. I guess I could do a simple linq to collect all user's claims, but I'm sure there is a better way using the identity methods.
You need to use the GetClaimsAsync() method. For example:
var claims = await _userManager.GetClaimsAsync(applicationUser);
See MSDN
i use instaSharp api to create an instagram web app
after i get token access i want to see followers and following list of my profile and another people profile
i need some method to Get another user followers and following !
in the official instagram web app you cant see followers and following list (just see amount) , So does this api support it ? How i Can do it ?
this api has a poor document and samples ,
How i can use this method ? instaSharpDoc
thanks
You can see user's followers and followings list with the official Instagram API.
https://instagram.com/developer/endpoints/relationships/ - documentation
https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN - Get the list of users this user follows.
https://api.instagram.com/v1/users/{user-id}/followed-by?access_token=ACCESS-TOKEN - Get the list of users this user is followed by.
You cannot request data from another user, e.g. followers and following, without the user authorization step.
Firstly, you need to redirect the user to an authorization page. After the user inputs his credentials, he will be redirected to a page(redirect_uri value) you have sent in the authorization request, where you will request the access_token to make requests on his account.
There is another option: you can add the username you want to make requests onto your app's Sandbox (require user verification). The username will receive a notification to authorize or revoke the access to your account. After authorizing it, you will be able to make requests on his account.
If you would like to understand more detailed information, please, have a quick look at the documentation about Sandbox at https://www.instagram.com/developer/sandbox/. It will help you clarify your mind and your implementation code.
I hope it helps you.
This solved for me using InstaSharper (without accessToken but using username and password for loggin in):
var following = await api.GetUserFollowingAsync("yourUserName",PaginationParameters.Empty);
var followers = await api.GetUserFollowersAsync("yourUserName", PaginationParameters.Empty);
This is the repository: https://github.com/a-legotin/InstaSharper
Tutorial to get starting: https://www.youtube.com/watch?v=f9leg398KAw
I don't know if this is useful but for me it works:
IResult<InstaUserShortList> followers = await api.GetUserFollowersAsync(userToScrape,
PaginationParameters.MaxPagesToLoad(5));
for (int i = 0; i < followers.Value.Count; i++)
{
Console.WriteLine($"\n\t{followers.Value[i].UserName}\n\t");
}
It gives you back the username of all of the followers of a user (change UserToScrape with the one that you prefer).
After a lot of digging around I've got my WPF application signing users in via Azure Mobile Service. My Mobile Service is connected to an Azure Active Directory that I have set up. However, when I log the user in with MobileServiceClient.LoginAsync(...) the MobileServiceUser UserId is in an unreadable hash it seems. For example it looks like: "Aad:X3pvh6mmo2AgTyHdCA3Hwn6uBy91rXXXXXXXXXX". What exactly is this?
I'd like to grab the user's display name to use but I can't figure out how.
That is the userID of Azure Active Directory. You need to create a service to expose your AAD info through a service and retrieve the additional information using the access token you get from your user.
First:
ServiceUser user = this.User as ServiceUser;
var identities = await user.GetIdentitiesAsync();
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
var aadAccessToken = aad.AccessToken;
var aadObjectId = aad.ObjectId;
This will give you the access token and objectID , then you need to query the information through AAD graphy API.
https://msdn.microsoft.com/library/azure/dn151678.aspx
Look at the sample request part. You should provide the query with the access token you got and objectId.
Here is an alternative approach, after reading http://justazure.com/azure-active-directory-part-2-building-web-applications-azure-ad/ scroll to the section on Identity in .Net it talks how claims are a standard part of the framework. So once you get the credentials object like provided by #beast
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
You can actually grab a dictionary with the various properties. Examples of some the properties can be found at https://msdn.microsoft.com/en-us/library/system.identitymodel.claims.claimtypes(v=vs.110).aspx
So from there you can do the following:
if (aad != null)
{
var d = aad.Claims;
var email = d[ClaimTypes.Email];
}
I did this to pull the user id which was cross referenced in a table. FYI I am using App Service, but I believe the credentials object is the same in Mobile Service
I'd like to be able to authenticate myself (my profile, not just my app) on my own web application using the Facebook C# SDK. Using the Graph API, I can get an access token, but that token does not seem to work properly with the Facebook C# as it seems to be stateless.
The error that is thrown is:
(OAuthException) An active access token must be used to query information about the current user.
I've poked around the Facebook C# SDK and documentation and most of the info I'm seeing is to redirect users to a login page which is not what I'm looking for.
Does anyone have a good sample of auto-logging in myself so I can pull up my own information?
TIA
When you say "yourself" do you mean the app or your actual facebook user?
If it's just your app, you can get an access token by POSTing to this URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APP_ID_HERE&client_secret=APP_SECRET_HERE
You can use this access token to perform actions on behalf of your users if they have authorized your app to do so.
I had the same problem where the access token didn't include the session part. Please check out my answer to this similar question - exchange code for token facebook-c#-sdk.
Here's a sample from my Home controller
[CanvasAuthorize]
public ActionResult Index()
{
var app = new FacebookClient(new Authorizer().Session.AccessToken);
dynamic me = app.Get("me");
ViewBag.Firstname = me.first_name;
ViewBag.Lastname = me.last_name;
return View();
}
Edit
Now I understand the question better. What about this?
var auth = new Authorizer(FacebookContext.Current.AppId, FacebookContext.Current.AppSecret, HttpContext);
auth.Authorize();
From the documentation:
public bool Authorize()
Member of Facebook.Web.Authorizer
Summary:
Authorizes the user if the user is not logged in or the application does not have all the sepcified permissions.
Returns:
Return true if the user is authenticated and the application has all the specified permissions.
I dont know if this will work for you:
using Facebook.Web;
using Facebook;
using System.Dynamic;
var auth = new CanvasAuthorizer { Permissions = new[] { "user_about_me"} };
if (auth.Authorize())
{
}
and include this in the aspx:
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
good luck !!