Get Access Token from Azure First Party App without user Interaction - azure

We have a First Party App with Delegated Graph API Permission.
We want to get Access Token from this FPA.
As of now we are able to generate token from browser here user need to login in browser to generate token.
Problem: We want to generate token without user interference and want to find a way to get the Token having Delegated Permission on behalf of user also we are using power automate to achieving this functionality.

There is a way of getting access tokens and that is by using MSAL
Here we would need tenet id , client id , username and password and scope. Tenetidand client id can be aquired from the portal after clicking on your registered app.
After that we will also need MSAL which is auth library for azure ad it is available in all language now for example using MSAL for python we can get tokens like this:
client = # client id from app
tenant = # tenant id from app
username = # account username
password = # account password
scope = [ '2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default' ]
app = PublicClientApplication( client_id = client, authority = "https://login.microsoftonline.com/" + tenant )
acquire_tokens_result = app.acquire_token_by_username_password( username = username, password = password, scopes = scope )
# acquire_tokens_result['access_token'] this is your tokens
Refer this Ms Documentation on MSAL python

Related

Change Azure B2C account password on behalf of a user

I'm trying to change the password of a user created in my Azure B2C Tenant. I'm using Microsoft.Graph C# SDK to do API calls.
First I create GraphServiceClient by providing details of my tenant:
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential("tenantId", "clientId", "clientSecret", options);
_client = new GraphServiceClient(clientSecretCredential);
Then I use the built-in method of a client to change the user's password:
await _client.Users["userId"].ChangePassword(currentPassword, newPassword).Request().PostAsync();
But I get following error:
Microsoft.Graph.ServiceException: Code: Authorization_RequestDenied
Message: Access to change password operation is denied.
Is it possible to change the password on behalf of a user? I found conflicting information on this topic on the internet. If this is impossible, what is the valid approach to do this?
I have a SPA frontend app in which the user is authenticated with redirection flow. The access token is then passed to my backend to authorize the requests. Maybe I can use this token to somehow access MS Graph API and change the password?
Note: I would like to let users change their passwords without leaving my SPA application.
I tried in my environment and got below results:
Initially I tried with your code and got same error:
According to MS-DOCS change password we need Directory.AccessAsUser.All permission and it only supported for delegated (Work or school accounts).
Trying to reset the password in the B2C tenant using the Graph API its is not possible Unfortunately, because there is no Directory.AccessAsUser.All, B2C tenant does not allow this type of password reset. For B2C tenants, the Graph API includes the permission. Only offline access and openID are available as delegated rights in the B2C tenant.
You can reset the password in B2C tenant are either admin performing password reset via Azure Portal or by using Password Reset Policy and also refer this MS-Q&A for updating password in powershell and postman.
Reference:
"Upn from claims with value null is not a valid upn." - Microsoft Q&A by amanpreetsingh-msft.

How to get current user's tenant id rather than application's tenant id in MS Teams tab app (React JS)

I am building a MS Teams Tab app using React JS, https://learn.microsoft.com/en-us/microsoftteams/platform/tabs/what-are-tabs. For each app, we need to create an App Registration in Azure console. Now, in my application I am trying to retrieve the logged in user's tenant ID rather than app tenant ID.
First thing I know is that I can get the tenant ID from SSO token. So I tried to retrieve the SSO token as follow using #microsoft/teams-js package.
initialize();
const authOptions: authentication.AuthTokenRequest = {
successCallback:(token) => {
// when I decode the token, the tid field is still giving me app registration tenant's id (user can be guest and can belong to different tenant)
},
failureCallback:(error) => {
},
};
authentication.getAuthToken(authOptions);
(Note the comment in the code above).
I can get the user's tenant ID if I force the user to login using MSAL with this libraries, #azure/msal-react and #azure/msal-browser. The access token gives me the tid of the user. But the thing is that I do not want to force the user to login. How can I get the user's tennant ID without forcing the user to login?

Access token retrieved from Azure using OAuth2 does not contain permission

I am working on a solution that needs to retreive email from a mailbox from a tenant using MS Graph API.
The solution needs to run in the background, with no use input (eg call login page for email in browser)
I have registered an Azure application, and have Admin consent for the MS Graph API:
Api permissions
My VB code is as follows (client_id, client_secret, tenant has been removed as confidential):
Dim http As New Chilkat.Http
Dim req As New Chilkat.HttpRequest
Dim json As New Chilkat.JsonObject
' Use the application ID for the client_id.
' (In Azure App Registrations, use the Application (client) ID)
req.AddParam(client_id, )
req.AddParam(client_secret, )
req.AddParam(tenant, )
req.AddParam(scope, https://graph.microsoft.com/.default)
'req.AddParam(username, )
'req.AddParam(password, )
req.AddParam(grant_type, client_credentials)
Dim resp As Chilkat.HttpResponse
' Replace {tenant} with your tenant ID, such as 112d7ed6-71bf-4eba-a866-738364321bfc.
resp = http.PostUrlEncoded(https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token, req)
If (http.LastMethodSuccess True) Then
Debug.WriteLine(http.LastErrorText)
Exit Sub
End If
Dim statusCode As Integer = resp.StatusCode
Debug.WriteLine(response status code: statusCode)
Debug.WriteLine(response body:)
Debug.WriteLine(resp.BodyStr)
I can see the above connecting to the Azure app. However, no permission (scope) is returned in the access token.
When I connect to MS Graph via browser, the token has all the required scope.
Can you please help/advise why I am unable to retreive token with permissions from the MS Graph API in vb?
Please note that, you cannot get scp claim in the token, as
user is not involved in generating token from client_credentials
grant type.
I assigned the same API permissions to my application like below:
When I decoded the access token(generated using client credentials grant type), scp claim is not present in the token like below:
You have to use authorization code flow grant type to get
scp claim in the decoded token, where user interaction is involved.
When I decoded the access token generated using authorization code flow, got scp claim successfully in the token like below:
To know more about authorization code flow, please refer below link:
Microsoft identity platform and OAuth 2.0 authorization code flow - Microsoft Entra | Microsoft Docs
You are using a client_credentials flow, which is an app-only context authentication.
The scp claim is only for user based authentication.
If you want to use the client_credentials flow, you will need to grant Application permissions on your app registration, instead of Delegated.
These applications permissions will then be present inside a roles claim. You can check the description of these claims here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens

How to generate access token for user in AZURE AD B2C using AzureADGraph or Microsoft Graph?

Is there a way to generate access token of a user using AZURE AD GRAPH client or MICROSOFT Graph client?
I have username and password ,client id, policy name. Using all these parameters. I want to generate the token.
Thanks!
We could do that but it is not recommanded that to use the username and password to do that.
In general Microsoft does not advise customers to use it as it's less secure than the other flows, and it is not compatible with conditional access (if the resource requires conditional access, the call to AcquireTokenSilent will just fail, given that this is not an interactive flow, the STS does not have an opportunity to present a dialog to the user to tell him/her that s/he needs to do multiple factor authentication).
Demo code.
var graphResourceId = "https://graph.windows.net";
var clientId = "afa0b3fxxxxx";
var userName= "xxxxx";
var password = "xxx";
var result = await authenticationContext.AcquireTokenAsync(graphResourceId, clientId, new UserPasswordCredential(userName, password));
var accessToken = result.AccessToken
For more information, please refer to this document.
Update:
Get Refresh token.
url:
post https://login.microsoftonline.com/{tenantId}/oauth2/token
Header:
Content-Type: application/x-www-form-urlencoded
body
resource=https%3A%2F%2Fgraph.windows.net&client_id=xxxxx&grant_type=password&username=tom%40xxxx.onmicrosoft.com&password=xxxxx&scope=openid
Test Result:

Azure AD Sign In

I have a web application that is secured by Azure AD. I would like to be able to allow some people to access this application. I have created an account in my directory for these users and I would like to log them in without doing a redirect to Azure AD.
Is there any way to get an Azure auth cookie and allow them to access my application without redirecting them to a login? I know the username / password and would like to be able to do the sign in behind the scenes.
You should be able to use the Resource Owner Credentials flow. Assuming you're using ADAL, you can leverage this sample app to retrieve a token.
Once you have the authentication result, you can use it to build an identity and pass that to the cookie authentication manager (assuming you're using the OWIN cookie authentication middleware).
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.GivenName, result.UserInfo.GivenName));
var id = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
Source: http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

Resources