Graph API: Insufficient privileges to complete the operation - azure-active-directory

I have the following permissions on my registered Azure Function..
This azure function will work as web hook and called by some application/API
but when I try to get data
public async Task<string> FindUpnByEmail(string email)
{
if (string.IsNullOrEmpty(email)) return email;
try
{
var request = new RestRequest("users")
.AddQueryParameter("$filter", $"mail eq '{email}'")
.AddQueryParameter("$select", "userPrincipalName");
var rest = new RestClient(GraphUrl)
{
Authenticator = await GetAuthenticator(),
};
var response = await rest.ExecuteGetAsync(request);
var userResponse = JsonConvert.DeserializeObject<ODataResponse<User>>(response.Content);
return userResponse.Value.Length > 0 ? userResponse.Value[0].UserPrincipalName : email;
}
catch (Exception ex)
{
return email;
}
}
I receive the following error:
Authorization_RequestDenied","message":"Insufficient privileges to
complete the operation.

Try to update the Admin consent to Yes for profile, Read Basic profile.
Or Add read write delegate permission and grant admin consent for that as well.

Related

IdentityServer Refresh Extension Grant

I have implemented an extension grant in my Identity Server instance. The purpose of this is for a mobile app to switch contexts between an authenticated user and a public kiosk type device.
When the user enters this mode, I acquire a new token and include the proper grant type.
I used the IS documentation as a base. Nothing crazy going on here at all, I just add some additional claims to this token to be able to access things in the API the user may otherwise not be set up for.
public class KioskGrantValidator : IExtensionGrantValidator
{
private readonly ITokenValidator _validator;
public KioskGrantValidator(ITokenValidator validator)
{
_validator = validator;
}
public string GrantType => "kiosk";
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
var userToken = context.Request.Raw.Get("token");
if (string.IsNullOrEmpty(userToken))
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
return;
}
var result = await _validator.ValidateAccessTokenAsync(userToken);
if (result.IsError)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
return;
}
// get user's identity
var sub = result.Claims.FirstOrDefault(c => c.Type == "sub").Value;
// I add some custom claims here
List<Claim> newClaims = new()
{
new Claim(ClaimTypes.Name, "kiosk")
}
context.Result = new GrantValidationResult(sub, GrantType, claims: newClaims);
return;
}
}
Now, the question is refreshing this token.
For this grant to work I'm passing in the access token, which expires, eventually causing the ValidateAccessTokenAsync to fail.
Wanted to see what the best way to refresh this token is? Currently the best way I have found is to refresh the original user access token when this one is about to expire, then get a second token with the new grant. This works, but seems maybe unnecessary.
Thanks for any input!

Cannot sign in with different account or "Use another account"

I'm trying to integrate Microsoft sso with a Xamarin.Forms app.
I'm using Microsoft.Identity.Client 4.7.1
I struggling to sign in with different accounts on the same device since it seems that the first account is always picked no matter what I do.
User A signs in
User A signs out
User B enters the app opens the webview with the Microsoft login page and prompts the "Use another account" button but even after typing his account, the webview redirects it to back to the mobile app as user A.
Here's the code that handles sign-in and sing-out:
private IPublicClientApplication _publicClientApplication;
public AuthService()
{
_publicClientApplication = PublicClientApplicationBuilder.Create(Constants.MicrosoftAuthConstants.ClientId.Value)
.WithAdfsAuthority(Constants.MicrosoftAuthConstants.Authority.Value)
.WithRedirectUri(Constants.MicrosoftAuthConstants.RedirectUri.Value)
.Build();
}
public async Task<string> SignInAsync()
{
var authScopes = Constants.MicrosoftAuthConstants.Scopes.Value;
AuthenticationResult authResult;
try
{
// call to _publicClientApplication.AcquireTokenSilent
authResult = await GetAuthResultSilentlyAsync();
}
catch (MsalUiRequiredException)
{
authResult = await _publicClientApplication.AcquireTokenInteractive(authScopes)
.WithParentActivityOrWindow(App.ParentWindow)
.ExecuteAsync();
}
return authResult.AccessToken;
}
private async Task<IAccount> GetCachedAccountAsync() => (await _publicClientApplication.GetAccountsAsync()).FirstOrDefault();
public async Task SignOutAsync()
{
var firstCachedAccount = await GetCachedAccountAsync();
await _publicClientApplication.RemoveAsync(firstCachedAccount);
}
A workaround is to use Prompt.ForceLogin but what's the point of sso if you have to type the credentials every time.
The line of code await _publicClientApplication.RemoveAsync(firstCachedAccount); can jsut remove the user from the cache, it doesn't implement a signout method. So you need to do logout manually by the api below:
https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https://localhost/myapp/

Login after signup in identity server4

I am trying to login user as soon as he/she registers.
below is the scenario
1)Registration page is not on identity server.
2)Post user details to Id server from UI for user creation.
3)On successful user creation login the user and redirect.
4)Trying to do it on native app.
I tried it with javascript app but redirection fails with 405 options call.
(tried to redirect to /connect/authorize)
on mobile app, don't want user to login again after signup for UX.
Has anyone implemented such behavior
tried following benfoster
Okay so finally i was able to get it working with authorization code flow
Whenever user signs up generate and store a otp against the newly created user.
send this otp in post response.
use this otp in acr_value e.g acr_values=otp:{{otpvalue}} un:{{username}}
client then redirects to /connect/authorize with the above acr_values
below is the identity server code which handles the otp flow
public class SignupFlowResponseGenerator : AuthorizeInteractionResponseGenerator
{
public readonly IHttpContextAccessor _httpContextAccessor;
public SignupFlowResponseGenerator(ISystemClock clock,
ILogger<AuthorizeInteractionResponseGenerator> logger,
IConsentService consent,
IProfileService profile,
IHttpContextAccessor httpContextAccessor)
: base(clock, logger, consent, profile)
{
_httpContextAccessor = httpContextAccessor;
}
public override async Task<InteractionResponse> ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null)
{
var processOtpRequest = true;
var isAuthenticated = _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
// if user is already authenticated then no need to process otp request.
if (isAuthenticated)
{
processOtpRequest = false;
}
// here we only process only the request which have otp
var acrValues = request.GetAcrValues().ToList();
if (acrValues == null || acrValues.Count == 0)
{
processOtpRequest = false;
}
var otac = acrValues.FirstOrDefault(x => x.Contains("otp:"));
var un = acrValues.FirstOrDefault(x => x.Contains("un:"));
if (otac == null || un == null)
{
processOtpRequest = false;
}
if (processOtpRequest)
{
var otp = otac.Split(':')[1];
var username = un.Split(':')[1];
// your logic to get and check opt against the user
// if valid then
if (otp == { { otp from db for user} })
{
// mark the otp as expired so that it cannot be used again.
var claimPrincipal = {{build your principal}};
request.Subject = claimPrincipal ;
await _httpContextAccessor.HttpContext.SignInAsync({{your auth scheme}}, claimPrincipal , null);
return new InteractionResponse
{
IsLogin = false, // as login is false it will not redirect to login page but will give the authorization code
IsConsent = false
};
}
}
return await base.ProcessInteractionAsync(request, consent);
}
}
dont forget to add the following code in startup
services.AddIdentityServer().AddAuthorizeInteractionResponseGenerator<SignupFlowResponseGenerator>()
You can do that by using IdentityServerTools class that IdentityServer4 provide to help issuing a JWT token For a Client OR a User (in your case)
So after the user signs up, you already have all claims needed for generating the token for the user:
including but not limited to: userid, clientid , roles, claims, auth_time, aud, scope.
You most probably need refresh token if you use hybrid flow which is the most suitable one for mobile apps.
In the following example, I am assuming you are using ASP.NET Identity for Users. The IdentityServer4 Code is still applicable regardless what you are using for users management.
public Constructor( UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IClientStore clientStore,
IdentityServerTools identityServerTools,
IRefreshTokenService refreshTokenService)
{// minimized for clarity}
public async Task GenerateToken(ApplicationUser user
)
{
var principal = await _signInManager.CreateUserPrincipalAsync(user);
var claims = new List<Claim>(principal.Claims);
var client = await clientStore.FindClientByIdAsync("client_Id");
// here you should add all additional claims like clientid , aud , scope, auth_time coming from client info
// add client id
claims.Add(new Claim("client_id", client.ClientId));
// add authtime
claims.Add(new Claim("auth_time", $"{(Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds}"));
// add audiences
var audiences = client.AllowedScopes.Where(s => s != "offline_access" && s != "openid" && s != "profile");
foreach (var audValue in audiences)
{
claims.Add(new Claim("aud", audValue));
}
// add /resources to aud so the client can get user profile info.
var IdentityServiceSettings = _configuration.GetSection("IdentityService").Get<IdentityServiceConsumeSettings>();
claims.Add(new Claim("aud", $"{IdentityServiceUrl}/resources"));
//scopes for the the what cook user
foreach (var scopeValue in client.AllowedScopes)
{
claims.Add(new Claim("scope", scopeValue));
}
//claims.Add(new Claim("scope", ""));
claims.Add(new Claim("idp", "local"));
var accesstoken = identityServerTools.IssueJwtAsync(100, claims);
var t = new Token
{
ClientId = "client_id",
Claims = claims
};
var refereshToken = refreshTokenService.CreateRefreshTokenAsync(principal, t, client);
}
This is just a code snippet that needs some changes according to your case

Microsoft graph API: getting 403 while trying to read user groups

I am trying to get user's group information who log-Ins into the application.
Using below code, when I am hitting https://graph.microsoft.com/v1.0/users/{user}, then I am able to see that user is exist (200), but when trying to hit https://graph.microsoft.com/v1.0/users/{user}/memberOf, then I am getting 403.
private static async Task Test()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "TOKEN HERE");
var user = "testuser#onmicrosoft.com";
var userExist = await DoesUserExistsAsync(client, user);
Console.WriteLine($"Does user exists? {userExist}");
if (userExist)
{
var groups = await GetUserGroupsAsync(client, user);
foreach (var g in groups)
{
Console.WriteLine($"Group: {g}");
}
}
}
}
private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user)
{
var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}");
return true;
}
private static async Task<string[]> GetUserGroupsAsync(HttpClient client, string user)
{
var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}/memberOf");
var obj = JsonConvert.DeserializeObject<JObject>(payload);
var groupDescription = from g in obj["value"]
select g["displayName"].Value<string>();
return groupDescription.ToArray();
}
Is this something related to permission issue, my token has below scope now,
Note - Over here I am not trying to access other user/group information, only who log-ins. Thanks!
Calling /v1.0/users/[a user]/memberOf requires your access token to have either Directory.Read.All, Directory.ReadWrite.All or Directory.AccessAsUser.All and this is
documented at https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_memberof.
A great way to test this API call before implementing it in code is to use the Microsoft Graph explorer where you can change which permissions your token has by using the "modify permissions" dialog.

Authentication with custom API controller with Azure Mobile App and Xamarin

I have create a Mobile App service with Azure. I have created a new custom controller as seen below.
[MobileAppController]
public class NewsController : ApiController
{
public ApiServices Services { get; set; }
// GET api/News
public async Task<IEnumerable<NewsItem>> Get()
{//returns some data}
}
Within Azure I have enabled authentication and set the options to Active Directory as seen below.
I'm trying to consume the API within a Xamarin iOS application.
I create a access token via Active Directory as seen below and this works and generates the token correctly.
public static class ServicePrincipal
{
static string authority = "https://login.microsoftonline.com/xxx";
static string clientId = "xxx";
static string clientSecret = "xx";
static string resource = "xx";
public static async Task<AuthenticationResult> GetS2SAccessTokenForProdMSA()
{
return await GetS2SAccessToken();
}
static async Task<AuthenticationResult> GetS2SAccessToken()
{
try
{
AdalInitializer.Initialize();
var clientCredential = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext(authority, false);
var authenticationResult = await context.AcquireTokenAsync(
resource,
clientCredential);
return authenticationResult;
}
catch (Exception ex)
{
throw;
}
}
}
However when trying to consume the API i always get an unauthorized exception.
I have tried authenticating by passing the token to the custom API like this. This throws an unauthorized exception
var client = new MobileServiceClient("THE URL");
var authenticationResult = await ServicePrincipal.GetS2SAccessTokenForProdMSA();
var authHeader = new Dictionary<string, string> { { "Bearer", authenticationResult.AccessToken } };
var orderResult = await client.InvokeApiAsync("News", HttpMethod.Get, authHeader);
I also tried the following, which doesn't work either.
CurrentPlatform.Init();
var client = new MobileServiceClient("THE URL");
var authenticationResult = await ServicePrincipal.GetS2SAccessTokenForProdMSA();
JObject payload = new JObject();
payload["access_token"] = authenticationResult.AccessToken;
await client.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);
Can you see any issues here, how do i pass though the authorization token?
I suggest enabling application logging in the Azure portal and then looking to see what the authentication error is.

Resources