unable to use validate jwt in APIM for managed Identity token - jwt

We have a validate jwt policy in APIM to validate jwt token. we are generating token from our function app using the azure.identity library. till now we were using system assigned identity for generating the token using the below method.
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://management.azure.com" + "/.default" }) { });
token is generated successfully. and we are able to successfully validate the token in the policy. below is the APIM xml policy.
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Invalid or Expired token" require-expiration-time="true" require-signed-tokens="true">
<openid-config url="https://login.microsoftonline.com/tenantid/v2.0/.well-known/openid-configuration" />
<audiences>
<audience>https://management.azure.com</audience>
</audiences>
<issuers>
<issuer>https://sts.windows.net/tenantid/</issuer>
</issuers>
<required-claims>
<claim name="oid" match="any">
<value>objectid of the managed identity/system assigned</value>
</claim>
</required-claims>
</validate-jwt>
now we have assigned the user managed identity and assigned the identity to the function app with the below code I am able to generate the token but in APIM it was throwing weird error.
var azureServiceTokenProvider = new ManagedIdentityCredential(clientId: "client-id-of-managed-identity-id");
accessToken = await azureServiceTokenProvider.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] { "https://management.azure.com" + "/.default" }));
APIM is telling
"JWT Validation Failed: IDX10501: Signature validation failed. Unable to match key: \nkid: ''.\nExceptions caught:\n ''.
any idea on how to overcome this ?

I have updated my code to use DefaultAzureCredential instead of ManagedIdentityCredential and it started working.
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{ ManagedIdentityClientId = "managed_identity_clinet_id" });
AccessToken accessToken = await credential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://management.azure.com" + "/.default" }) { });
I passed the client ID of the managed Identity and able to proceed with the generated token.

Related

trying to a send a "string" refresh token in request body using axios post

I am trying to create a post request for refreshing the token using axios.post
my code is the following
I can't seem to pass the parameters in the correct order/way
in the api request its like this
export async function refreshTheCurrentToken() {
const url = RefreshCurrentToken;
const refreshTokenHardCoded = "xxxxxx"
const refreshedToken = await axios
.post(url, {
params: {
string: refreshTokenHardCoded,
},
})
.catch((error) =>
console.log(error + " 🟥error refreshing the current token")
);
// console.log(url + " URL FOR REFRESHING TOKEN");
console.log(refreshedToken + " NEW TOKEN GENERATED ✅");
// return refreshToken;
}
my response is the following
LOG AxiosError: Request failed with status code 400 🟥error refreshing the current token
LOG undefined NEW TOKEN GENERATED ✅
tried setting the refresh token in a static way. on postman it works but on my react native project it doesn't.
tried converting the refresh token a string, tried creating an object to hold the refresh token

KeyCloak - Token obtained by Javascript adapter can't be used for authorizing

Keycloak 17.0.1
I have 2 tokens, one obtained via the JavaScript adapter and the other via java adapter. They are pretty much the same through jwt.io (same aud, azp...). I see the most significant difference is that the JavaScript token has "scope": "openid profile email", while the java token has "scope": "profile email" (without openid)
JavaScript token obtained by:
const keycloak = new Keycloak(
{url: 'http://keycloak-server$', realm: 'myrealm', clientId: '**frontend-app**' });
keycloak.init({ onLoad: 'login-required' })
//and get token from the property "token" of keycloak object.
Java token obtained by:
credentials = new HashMap<>();
credentials.put("secret", ""); //empty secret (this is a public frontend client)
config = new Configuration(url, realmName, "frontend-app", credentials, null);
authzClient = AuthzClient.create(config);
token = authzClient.obtainAccessToken("username", "1234").getToken();
Two tokens are given to server code, which is with the Java adapter:
credentials = new HashMap<>();
credentials.put("secret", "xxx"); //confidential backend-app client
config = new Configuration(url, realmName, "backend-app", credentials, null);
authzClient = AuthzClient.create(config);
request = new AuthorizationRequest();
request.addPermission("resourceid", {});
authzClient.authorization(token).authorize(request);
Two different results:
With token obtained by Java adapter: permission allowed
With token obtained by JavaScript adapter:
Got response: "error":"invalid_grant","error_description":"Invalid bearer token"},
And in KeyCloak log: type=PERMISSION_TOKEN_ERROR, realmId=xxx, clientId=xxx, userId=null, ipAddress=192.168.120.196, error=invalid_token, auth_method=oauth_credentials, grant_type=urn:ietf:params:oauth:grant-type:uma-ticket
I need to fix the Javascript client to work. Any help, please?
Thank you,
Huy Banh.

jwt acess_token and refresh_token mechanism: axios : How to keep checking for the access_token is working

I am using JWT token based authentication system. i.e djangorestframework-simplejwt in my backend
Now I am using reactj and axios as frontend:
After providing username and pass to the login api, I got access_token and refresh_token which I stored in the localstorage
Now I am trying to connect to an api using access_token.
I get Token invalid or expired
Example I am trying to change password using this api and provide access_token
const url = "dj-rest-auth/password/change/";
const auth = {
headers: {
Authorization: "Bearer " + localStorage.getItem("access_token"),
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
old_password: old_password,
new_password1: new_password1,
new_password2: new_password2,
};
const promise = axios.post(url, data, auth);
promise
.then((res) => {
console.log(res)
})
.catch((err) => {
if (err.response) {
console.log(`${err.response.status} :: ${err.response.statusText}`)
console.log(err.response.data)
}
})
I can do another api call using refresh_token to get access_token when i get an err.
But sometimes, the err can be due to network error or something else. Then even i try to get access_token using refresh_token, it will just get into a loop.
HOw to do this the right way
If you are using Django as the backend, I would suggest using dj-rest-auth for JWT token authentication. dj-rest-auth requires "djangorestframework-simplejwt" for token management.
It is recommended to store access token and refresh token in httponly cookie so that it is not accessed by javascript.
Add JWTtokenAuthentication as authentication classes in settings.py.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'dj_rest_auth.jwt_auth.JWTCookieAuthentication'
]
}
Add the below configuration too in settings.py
REST_SESSION_LOGIN = False
SITE_ID=1
REST_USE_JWT = True
JWT_AUTH_COOKIE = 'access-token' #any name
JWT_AUTH_REFRESH_COOKIE = 'refresh_token' #any name
JWT_AUTH_SECURE = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
There is an open issue with dj-rest-auth, that requires the below code to be implemented in your back-end Github issue: https://github.com/iMerica/dj-rest-auth/issues/97. As workaround suggested, you have to create a file middleware.py and paste below code.
import json
from django.utils.deprecation import MiddlewareMixin
from yourapp.settings import JWT_AUTH_REFRESH_COOKIE # from settings.py
class MoveJWTRefreshCookieIntoTheBody(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, *view_args, **view_kwargs):
if request.path == '/token/refresh/' and JWT_AUTH_REFRESH_COOKIE in request.COOKIES:
if request.body != b'':
data = json.loads(request.body)
data['refresh'] = request.COOKIES[JWT_AUTH_REFRESH_COOKIE]
request._body = json.dumps(data).encode('utf-8')
else:
print("The incoming request body must be set to an empty object.")
return None
By now, your back-end will be successfully generating access token and refresh token. Even your back-end will be capable of refreshing access token using refresh token.
Front-End:
By default, access token and refresh tokens are stored in httponly cookie, so you don't need to worry about that part.
Axios can be used to make call to login-end point to get tokens. Make sure you use "withCredentials" and "Headers" in your request.
Response will be tokens, by default it will be stored in httponly cookie, since we are using dj-rest-auth. For all the consecutive requests, httponly cookie will be included, if tokens are valid, user will be provided access. IF token is expired, you need to make call to refresh endpoint to get new access token.
Since you are in development mode, you have to have same domain for both BE and FE, different ports.You can start django-server using below command and make sure your FE is also running in localhost
python manage.py runserver localhost:8080
dj-rest-auth : https://dj-rest-auth.readthedocs.io/en/latest/index.html

protect asp.net web api 2 project with identity server 4

I have an asp.net web api 2 project with .Net framework 4.8 and a centralized Identity Server 4 project. I want to validate jwt/access token generated from IS4 in my web api 2 project. I can understand its a duplicate question but somehow I am unable to find any suitable help and I am not sure what's missing. I have used IdentityServer3.AccessTokenValidation for token validation in web api project.
Startup.cs
using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplicationApiNew.Startup))]
namespace WebApplicationApiNew
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44373",
RequiredScopes = new[] { "api1" },
});
}
}
}
Calling this API with a valid JWT bearer token still gives 401:
[Authorize]
[HttpPost]
public String GetName1()
{
if (User.Identity.IsAuthenticated)
{
var identity = User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
}
return "Valid";
}
else
{
return "Invalid";
}
}
Error details:
2021-07-24 20:41:25.4133|DEBUG|Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware|Authentication failed
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10214: Audience validation failed. Audiences: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. Did not match: validationParameters.ValidAudience: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' or validationParameters.ValidAudiences: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateAudience(IEnumerable`1 audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateAudience(IEnumerable`1 audiences, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.Owin.Security.Jwt.JwtFormat.Unprotect(String protectedText)
at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationHandler.<AuthenticateCoreAsync>d__3.MoveNext()
The error shows:
IDX10214: Audience validation failed
If your JWT token contains an "aud" claim, the authentication middleware
is attempting to validate the audience claim, but there is no audience specified in your options. Can you try one of the following:
Set an audience in the options:
Audience = "[your audience]"
Disable audience validation in the options:
TokenValidationParameters.ValidateAudience = false;
Refer to the identity server documentation for more details:
https://docs.identityserver.io/en/latest/topics/apis.html
I found solution to my problem. IS3 requires aud claim (with /resources in url) to be present in jwt/access token in order to validate the token. But on the other side IS4 has stopped emitting the aud claim by default. So we need to explicitly set IS4 server to emit aud claim to support legacy/old access token validation with IdentityServer3.AccessTokenValidation.
services.AddIdentityServer(options =>
{
...
options.EmitStaticAudienceClaim = true; // <- for older access token validation
})
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
...

JWT Token .NET Core Identity Server problem

I am trying to secure a .NET 5.0 Web API with OAuth Client Credentials flow.
My Client is requesting a token from the IdentityServer4 instance and supplying it to the API. The API is then returning a 401 error when I access and endpoint. I notice the following header:
WWW-Authenticate header contains Bearer error=\"invalid_token\", error_description=\"The audience 'empty' is invalid\"
Which suggests my JWT does not contain the audience paramater.
My JWT request code looks like the following:
var tokenResponseType = await serverClient.RequestClientCredentialsTokenAsync(new
ClientCredentialsTokenRequest
{
Address = discoveryDocument.TokenEndpoint,
ClientId = "client_id",
ClientSecret = "client_secret",
Scope = "ApiOne",
});
The code to validate the Token is here:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", config =>
{
config.Authority = "https://localhost:44335/";
config.Audience = "ApiOne";
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateActor = true,
ValidateLifetime = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true
};
config.RequireHttpsMetadata = false;
});
I believe the JWT token should contain the audience parameter. When I request the JWT I can't find a way to set the audience parameter.
I've used jwt.io to debug my JWT token and this confirms the audience value is not set. I expected setting the Scope on the request would do this.
What is lacking is the ApiScope and ApiResource configuration in IdentityServer.
First you need an ApiScope defined, like:
new ApiScope(name: "ApiOneScope",
displayName:"You can manage the ApiOne system.",
userClaims: new List<string>{ });
The ApiScope is a scope that the client can request access to.
then you need a ApiResource defined like:
new ApiResource()
{
Name = "ApiOne",
DisplayName = "Orders API Service",
Scopes = new List<string> { "ApiOneScope" },
};
The ApiResource is the actual Api, that end up in the audience claim when the clients requests the scope named ApiOneScope.
To complement this answer, I write a blog post that goes into more detail about this topic:
IdentityServer – IdentityResource vs. ApiResource vs. ApiScope