I'm getting an error (mentioned below) when I'm trying to use Cortana Bot user token (which is a Graph token) to generate an "on-behalf-of" token to another consuming Web API application using ClientAssertionCertificate / ClientCredential targeted to another consuming Web API by passing its AppId as ResourceId and userAssertion generated by using Cortana Bot user token.
When checked our Bot AAD settings it is configured with other consuming Web API (API B) as valid application along with Graph application. Do we need to do any additional setting in AAD to get this on-behalf-of token?
AADSTS50013: Assertion contains an invalid signature.
[Reason - The provided signature value did not match the expected signature value.,
Thumbprint of key used by client: '9DB0B05B5D70DD7901FB151A5F029148B8CC1C64',
Found key 'Start=11/11/2018 00:00:00,
End=11/11/2020 00:00:00'
]
Trace ID: a440869f-b8f5-4d87-ba1a-6bd8dd7ba200
Correlation ID: 651e1fa8-2069-4489-a687-e68e5206e193
Timestamp: 2019-01-02 07:14:45Z
Following is the flow and Sample code how we are trying to get an on-behalf-of token for other consuming Web API (API B).
Flow Steps:
Cortana asks for user Sign-in
User Sign-in to Cortana
Cortana sends this user token (generated targeting to use https://graph.microsoft.com as Audience) to Microsoft Bot Framework API
Microsoft Bot Framework API validates and wants to consume this token for calling other Web API (which is called API B).
As this Cortana user token cannot be used directly, it needs to be generated as an on-behalf-of token to API B from Microsoft Bot Framework API.
Following is the code sample used to generate an on-behalf-of token from Microsoft Bot Framework API:
public async Task<string> GetOnBehalfOfTokenAsync(string authority, string resource, string scope = "", string token = "")
{
AuthenticationResult output;
var clientId = ConfigurationManager.AppSettings["API-B-ClientId"];
// Read certificate which can be used for getting token to API B using ClientAssertionCertificate
// GetCert() is used to get the Certificate based on Thumbprint configured in Web.config file.
var certificate = this.GetCert();
// 'authority' is https://login.microsoftonline.com/{tenant id}
var authContext = new AuthenticationContext(authority);
var cllientCertificateCredential = new ClientAssertionCertificate(clientId, certificate);
// 'token' is the user token which was received from Cortana.
var userAssertion = (!string.IsNullOrWhiteSpace(token)) ?
new UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer",
TokenHelper.ExtractUserInfoFromAuthToken(token, "upn")) : null;
try
{
// 'resource' is the Resource Id of API B
// if UserAssertion is null then get token with ClientAssertionCertificate else get
// on-behalf-of token using UserAssertion and ClientAssertionCertificate
if (userAssertion == null)
{
output = await authContext
.AcquireTokenAsync(resource, cllientCertificateCredential)
.ConfigureAwait(false);
}
else
{
output = await authContext
.AcquireTokenAsync(resource, cllientCertificateCredential, userAssertion)
.ConfigureAwait(false);
}
}
catch (Exception ex)
{
logger.log("Error acquiring the AAD authentication token", ex);
}
return output.AccessToken;
}
Getting an exception which was mentioned above at this step:
output = await authContext
.AcquireTokenAsync(resource, cllientCertificateCredential, userAssertion)
.ConfigureAwait(false);
My understanding is: first you get user token from your Cortana access ms graph API; and then you want to use the user token to generate the OBO token in Microsoft Bot Framework API; final, you want to use the OBO token to access API B from Microsoft Bot Framework API.
You want to get OBO token in Microsoft Bot Framework API, you should use the API id and the secret, for this, I have never tried this.
On my side, I use v1 endpoint, I create two API (API A and B) and my flow is:
First, my app requests token1 for API A;
Next, use the token1 to request OBO token2 for API B from API A;
Final, use the OBO token2 to request OBO token3 for aad graph API from API B.
For the OBO in v1 endpoint, please read link1.
For the OBO in v2 endpoint, please read link2.
We could able to resolve this issue by configuring our dependent custom API (API B) "user_impersonation" scope to Cortana channel configuration to our Bot. With this configuration change, we do not need to generate On-Behalf-Of token to API B from our Microsoft Bot application.
Thanks to all who has supported to provide solutions for this thread...
Related
I have an ASP.NET 6.0 Web API project. I would like to add authentication and authorization to it, but it must use SSO via Azure.
We already have a SPA application that does this, it uses the Angular MSAL library to redirect the user to an SSO Login page, then returns to the SPA with an access token. The access token is then added to the header of each request to the Web API, which uses it to enforce authentication.
Now we want to share our web API with other teams within our organization, and we would like to have that login process just be another API call, rather than a web page.
Conceptually, a client would hit the /login endpoint of our API, passing in a userID and password. The web API would then get an access token from Azure, then return it as the payload of the login request. It's then up to the client to add that token to subsequent request headers.
I have done this with regular ASP.NET Identity, where all of the user and role data is stored in a SQL database, but since our organization uses SSO via Azure Active Directory, we would rather use that.
I have researched this topic online, and so far all of the examples I have seen use a separate SPA, just like we already have. But as this is a web api, not a front-end, we need to have an API method that does this instead.
Is this even possible? I know Microsoft would rather not have user credentials flow through our own web server, where a dishonest programmer might store them for later misuse. I understand that. But I'm not sure there's a way around this.
Thanks.
I believe you are looking for the Resource Owner Password (ROP) flow. You can use IdentityModel.OidcClient to implement it.
Sample code:
public class Program
{
static async Task Main()
{
// call this in your /login endpoint and return the access token to the client
var response = await RequestTokenAsync("bob", "bob");
if (!response.IsError)
{
var accessToken = response.AccessToken;
Console.WriteLine(accessToken);
}
}
static async Task<TokenResponse> RequestTokenAsync(string userName, string password)
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync(Constants.Authority);
if (disco.IsError) throw new Exception(disco.Error);
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
UserName = userName,
Password = password,
Scope = "resource1.scope1 resource2.scope1",
Parameters =
{
{ "acr_values", "tenant:custom_account_store1 foo bar quux" }
}
});
if (response.IsError) throw new Exception(response.Error);
return response;
}
}
Sample taken from IdentityServer4 repository where you can find more ROP flow client examples.
I would recommend that you don't go with this implementation and instead have all clients obtain their access tokens directly from Azure AD like you did with your Angular SPA.
I am trying to use AAD delegated permission Bearer tokens for a Visio VSTO addin to create SharePoint Online pages using CSOM. Initially I was able to get this working entering username / password following Modern Authentication with CSOM for Net Standard
However, I would like for the user to select an existing AAD account. When I attempt to use the following code the Bearer token "aud" claim is consistently set to "00000003-0000-0000-c000-000000000000" which is the Graph API. Whilst a ClientContext object is returned I am getting a HTTP 401 Unauthorized error when performing a page lookup.
The code is as follows
//
// Get Client App
//
var ClientApp = (PublicClientApplication)PublicClientApplicationBuilder.Create(<AAD App ID>)
.WithDefaultRedirectUri()
.WithTenantId(<AAD Tenant ID>)
.WithAuthority(AzureCloudInstance.AzurePublic, <AAD Tenant ID>)
.Build();
//
// Prompt for user to select preferred AAD account
// The returned JWT Bearer Token "aud" claim is 00000003-0000-0000-c000-000000000000
//
var Token = ClientApp.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.WithParentActivityOrWindow(GetActiveWindow())
.ExecuteAsync()
.GetAwaiter()
.GetResult();
//
// Get client Context
//
var ClientContext = AuthenticationManager.GetAzureADAccessTokenAuthenticatedContext(<SharePoint Site URL>, Token.AccessToken);
//
// Using the Client Context to query the Site results in HTTP 401
//
ClientContext.Load(ClientContext.Web, p => p.Title, t => t.Description);
ClientContext.ExecuteQuery();
Looking at the code for the AuthenticationManager class in the above link I can see that the AAD Bearer request is passing the following resource request parameter to the SharePoint online URL:
var body = $"resource={resource}&client_id={clientId}&grant_type=password&username={HttpUtility.UrlEncode(username)}&password={HttpUtility.UrlEncode(password)}";
So it seems that AAD is setting the Bearer token "aud" claim based upon this parameter. However, when I try and add this parameter using 'WithExtraQueryParameters' I am getting the following error: "AADSTS901002: The 'resource' request parameter is not supported"
Ok, I figured out the problem. The scope needs to be prefixed with the resource:
string[] scopes = { "https://<domain>.sharepoint.com/AllSites.Write", "user.read" }
Then retrieve the token
this.Token = await ClientApp.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.WithParentActivityOrWindow(GetActiveWindow())
.ExecuteAsync();
I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework.
Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API.
So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the API.
So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not?
Is it just we need to make an API call to graph API endpoint with accessToken that user/SPA/native passed and if it is able to get the user data with the accessToken then then token is valid or if it fails then the accessToken is invalid.
Is it the general way to validate the token or some better approach is there? Please help
Good day sir, I wanna share some of my ideas here and I know it's not a solution but it's too long for a comment.
I created a SPA before which used msal.js to make users sign in and generate access token to call graph api, you must know here that when you generate the access token you need to set the scope of the target api, for example, you wanna call 'graph.microsoft.com/v1.0/me', you need a token with the scope 'User.Read, User.ReadWrite' and you also need to add delegated api permission to the azure app.
So as the custom api of your own backend program. I created a springboot api which will return 'hello world' if I call 'localhost:8080/hello', if I wanna my api protected by azure ad, I need to add a filter to validate all the request if has a valid access token. So I need to find a jwt library to decode the token in request head and check if it has a token, if the token has expired and whether the token has the correct scope. So here, which scope is the correct scope? It's decided by the api you exposed in azure ad. You can set the scope named like 'AA_Custom_Impression', and then you can add this delegate api permission to the client azure ad app, then you that app to generate an access token with the scope of 'AA_Custom_Impression'. After appending the Bearer token in calling request, it will be filtered by backend code.
I don't know about python, so I can just recommend you this sample, you may try it, it's provided by microsoft.
I've solved the similar issue. I don't found how to directly validate access token, but you can just call graph API on backend with token you've got on client side with MSAL.
Node.js example:
class Microsoft {
get baseUrl() {
return 'https://graph.microsoft.com/v1.0'
}
async getUserProfile(accessToken) {
const response = await got(`${this.baseUrl}/me`, {
headers: {
'x-li-format': 'json',
Authorization: `Bearer ${accessToken}`,
},
json: true,
})
return response.body
}
// `acessToken` - passed from client
async authorize(accessToken) {
try {
const userProfile = await this.getUserProfile(accessToken)
const email = userProfile.userPrincipalName
// Note: not every MS account has email, so additional validation may be required
const user = await db.users.findOne({ email })
if (user) {
// login logic
} else {
// create user logic
}
} catch (error) {
// If request to graph API fails we know that token wrong or not enough permissions. `error` object may be additionally parsed to get relevant error message. See https://learn.microsoft.com/en-us/graph/errors
throw new Error('401 (Unauthorized)')
}
}
}
Yes we can validate the Azure AD Bearer token.
You can fellow up below link,
https://github.com/odwyersoftware/azure-ad-verify-token
https://pypi.org/project/azure-ad-verify-token/
We can use this for both Django and flask.
You can directly install using pip
but I'm not sure in Django. If Django install working failed then try to copy paste the code from GitHub
Validation steps this library makes:
1. Accepts an Azure AD B2C JWT.
Bearer token
2. Extracts `kid` from unverified headers.
kid from **Bearer token**
3. Finds `kid` within Azure JWKS.
KID from list of kid from this link `https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys`
4. Obtains RSA key from JWK.
5. Calls `jwt.decode` with necessary parameters, which inturn validates:
- Signature
- Expiration
- Audience
- Issuer
- Key
- Algorithm
There is a C# application under development that is supposed to be a part of a bigger backend application to process some data. This application is supposed to obtain a token from Azure AD B2C and send it to an HTTP-triggered function where it is supposed to be validated by the following code:
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"{_authenticationSettings.Authority}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
_validationParameters = new TokenValidationParameters
{
IssuerSigningKeys = config.SigningKeys,
ValidateAudience = true,
// Audience MUST be the app ID aka clientId
ValidAudience = _authenticationSettings.ClientId,
ValidateIssuer = true,
ValidIssuer = config.Issuer,
ValidateLifetime = true
};
var tokenHandler = new JwtSecurityTokenHandler();
var result = tokenHandler.ValidateToken(authHeader.Parameter, _validationParameters, out var jwtToken);
First, we thought that obtaining an access token from Microsoft Graph API using MSAL would help us but the C# code above threw an invalid signature exception which we discovered makes sense due to this GitHub post. Apparently, we need to obtain an id_token instead in the application and send it to the HTTP-triggered function for validation by the code snippet above.
The application cannot obtain the id_token because it's not supposed to launch Azure AD B2C's login UI to have a user sign-in and redirect it through a URL. What is the solution to this problem so that the application would obtain a token without a UI and send that to the http-triggered function for validation?
Obtaining a token for the AAD B2C tenant without UI is possible in two ways and you should probably pick one depending on what exactly you want to achieve:
user token - by using Resource Owner Password Credentials flow - https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy. This flow is deprecated though and mentioned usually in legacy application context
server-side application token - by using Client Cretendial flow - this on the other hand requires using requests specific for AAD but with AAD B2C tenant - https://learn.microsoft.com/en-us/azure/active-directory-b2c/application-types#daemonsserver-side-applications
I'm also not quite sure why should you use id_token for that. If the application needs to authorize the request to the function with the token then it should be an access token regardless of how the token is retrieved (interactive UI or not).
Using IdentitServer4 I've create a client for a windows application. To call into another authentication service (ie, AWS STS) I need to setup federation to my ID server and using an identity token.
Is it possible to get an identity token for a client?
The following code give me the access token but the identity token is null.
var disco = await DiscoveryClient.GetAsync(Properties.Settings.Default.IdentityUrl);
if (disco.IsError)
{
return false;
}
var tokenClient = new TokenClient(disco.TokenEndpoint, _executionContext.ClientID, _executionContext.Secret);
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api.v1");
_executionContext.AgentToken = tokenResponse.AccessToken; // OK
_executionContext.IdentityToken = tokenResponse.IdentityToken; // NULL
No, by definition a client cannot request an identity token for itself. Only on behalf of a user. From the docs:
User
A user is a human that is using a registered client to access
resources.
Client
A client is a piece of software that requests tokens from
IdentityServer - either for authenticating a user (requesting an
identity token) or for accessing a resource (requesting an access
token).
The reason that a client can't request an identity token for itself is because it doesn't have (and can't have) a sub claim:
The presence (or absence) of the sub claim lets the API distinguish
between calls on behalf of clients and calls on behalf of users.
Here's an example on how to request an identity token on behalf of a user using the password grant.