Extract user from authentication token - azure-api-management

I have created custom Oauth2 service and configured API to use it according to the article: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-oauth2
Using Developer Portal I see that access token is sent to the API endpoint. However I need to have one more piece of information sent to my endpoint. The access token looks like this:
{"access_token":"e_Pt_0mEUKfMk7DzN7QDmb4tx6syaMM9d7Ei9UH4y1pYipErNHZFz9dU5ZmdTIvr2R4fD1GxJZY-Bsyt7tIpm7uKFScrrKRAKBVGeU3T7R1WTiBV3WglPK1OHZgOSpIY","token_type":"bearer","expires_in":3600,"user":"T81lum-5p6QvDR7l6hv7lfE52bAbA2ylWBnv9CZEzNb0B"}"
I need to extract the user property of the token and send it to API endpoint. Is it possible?
Thank you

Just share an idea about this. the user name is encoded in the bear token that can be parsed with JWT. You can add policy in <inbound> where you parse token and save user name to header then pass to your backend. the official document already provided the JWT parser
Jwt jwt = AsJwt(put_your_token_in_here)
String userName = jwt.Claims.GetValueOrDefault("name")
see JWT token.

You can parse the JSON and extract the user id, but it's going to be dependent on the language you're using.
In Node.JS, it's pretty straightforward (here assuming the auth blob is a string, and not yet parsed):
let userid = JSON.parse( auth_blob ).user;
In Java using GSON:
JsonElement jsonTree = parser.parse( auth_blob );
JsonElement userElement = jsonTree.get("user");
String user = userElement.getAsString();
and so on... searching for "parse JSON" and your language of choice will help you out there.
There's a short tutorial for how to embed a json extract in Azure here:
https://learn.microsoft.com/bs-latn-ba/azure/api-management/policies/cache-response?toc=api-management/toc.json
<!-- Extract a JSON object containing lat/long from the response and serialize it into a variable. -->
<set-variable name="latlong" value="#(((IResponse)context.Variables["response="""]).Body.As<JObject>
()["results"][0]["geometry"]["location"].ToString())"/>
So, I suppose that you could do the same thing for your auth blob:
<set-variable name="user" value="#((auth_blob).Body.As<JObject>
()["user"].ToString())"/>
Please edit if this is incorrect - I'm just guessing here.

You cannot retrieve user details from auth code. You can do it using an access token.
Please refer to similar question and answer here

Related

NodeJS Joi Vlidation - How to return JSON response instead of a string?

Recently, Iv'e been using the Joi validation library in-order to validate the data which comes in from a request (building a RESTful API).
I was using the .label() method to generate a string response and send it back to the user, but I couldn't find any way to send a JSON response back to the user?
Tried sending a premade JSON inside the string, searching the documentation and the internet of course - couldn't find any mention of it.
Current code example:
textField: Joi.string().required().max(4).label("This example field didn't pass the testing phase, please try again)"),
Any ideas?
If you need to send data in case of error,try .error() method. you can pass error in it.

Keycloak: Validate access token and get keycloak ID

I need to be able to do the following (with plain cURL & JSON server-side- no frameworks or Java):
Use a string representation of a Keycloak access token I have been given by a 3rd party to verify that the token is valid.
If the token is valid, get the Keycloak ID for that user.
How do I do this using plain old HTTP posts? I've found lots of Java examples but I need to know the raw HTTP POSTs and responses underneath.
Is it something like this to validate the token?
/auth/realms/<realm>/protocols/openid-connect/validate?access_token=accesstokenhere
What does this return in terms of data (sorry I currently have no test server to interrogate)?
Thanks.
The validate endpoint does not seem to work now. It used to return access token. I am using the keycloak 2.5.1 now. As mentioned in post by Matyas (and in the post referenced by him), had to use introspect token endpoint.
In my testing Bearer authentication did not work. Had to use Basic authentication header along with base64 encoded client credentials.
base64.encode("<client_id:client_secret>".getBytes("utf-8"))
The response from introspect endpoint is in JSON format as shared in post referenced by Maytas, has many fields based on type of token being introspected. In my case token_type_hint was set as access_token.
requestParams = "token_type_hint=access_token&token=" + accessToken
The response included required user details like username, roles and resource access. Also included OAuth mandated attributes like active, exp, iss etc. See rfc7662#page-6 for details.
Maybe you need this:
http://lists.jboss.org/pipermail/keycloak-user/2016-April/005869.html
The only one problem is that, introspect is not working with public clients.
The key url is:
"http://$KC_SERVER/$KC_CONTEXT/realms/$REALM/protocol/openid-connect/token/introspect"
You need to authorize your client e.g. with basic auth, and need to give the requester token to introspect:
curl -u "client_id:client_secret" -d "token=access_token_to_introspect" "http://$KC_SERVER/$KC_CONTEXT/realms/$REALM/protocol/openid-connect/token/introspect"

Use oAuth token with Azure MobileServiceClient.login()

I am using the native Facebook SDK (through an opensource tool called 'SimpleFacebook') to authenticate with Facebook. That part is working great. I find the Microsoft Azure implementation of Facebook authentication to be lacking.
Anyway, the next step is to use the token from this Facebook session and authenticate with MS/Azure. There are two methods like look like they should do the job
public void login(java.lang.String provider,
java.lang.String oAuthToken,
UserAuthenticationCallback callback)
Invokes Windows Azure Mobile Service authentication using a provider-specific oAuth token
Parameters:
provider - The provider used for the authentication process
oAuthToken - The oAuth token used for authentication
callback - Callback to invoke when the authentication process finishes
And another very similar method where the second param is a JSON object of type:
com.google.gson.JsonObject oAuthToken,
Is it just me or is the documentation lacking here? I tried just calling the Facebook session's .getAccessToken() and passing that to the functions and I get an error from Azure:
Caused by: com.microsoft.windowsazure.mobileservices.MobileServiceException: {"code":400,"error":"Error: invalid json"}
at com.microsoft.windowsazure.mobileservices.MobileServiceConnection$1.onNext(MobileServiceConnection.java:115)
How do we know what the correct JSON format is?
Am Using the right token?
More information can be found at:
at this Azure site
I think I have this figured out. Essentially all I had to do was create a JSON object (which is fairly new for me). I tried this earlier but I had imported the wrong JSON class (I had imported org.json.JsonObject or something rather than the com.google.gson.JsonObject).
once I did that I had to figure out what the correct json properties should be. Through a lot of Google searches I found out this is the correct format:
JsonObject jo = new JsonObject();
jo.addProperty("access_token", token);
Then use jo.toString() in the call like:
mClient.login(MobileServiceAuthenticationProvider.Facebook, jo.toString(), new UserAuthenticationCallback() {
.....
}
Really not that difficult, but why wouldn't Azure team put this in their docs???
Maybe this is just "obvious" information for a seasoned dev, but it took me a whole evening to figure out.

soap UI : how to Authenticate REST API using certificate and user name and use post json request

Using soap ui 4.6 ,I need to authenticate rest api using certificate and username/password and then i have to get the session id(cookie) and work with it for other operation.How can i do this? any reference?
I do this manually in order to avoid any unknown cookies and/or "magic" that the session manager might pass along. Here is my Java RestAssured example and the equivalent SoapUI request headers:
response = given().cookie("SESSIONID", "12345").cookie("ABC_123", "abcde").header("CLIENT_ID", "aaa123");
In SoapUI set these headers:
Name Value Style Level
CLIENT_ID aaa123 HEADER RESOURCE
Cookie SESSIONID=12345; ABC_123=abcde HEADER RESOURCE
i.e. you put all the cookies in correct format in single header called "Cookie". Standard http stuff, but nobody really gave this answer yet.

Is an endpoint that returns JSON safe from basic hijacking if an auth token is required?

I was reading that it was a good idea to convert all GET type requests to a json resource to POST in order to prevent another site from stealing information through <script src="myEndpoint"> but I'm still trying to make sense of it. It seems that this would would only protect against that scenario or possible enumeration of the endpoint.
I am planning for our json resources to require an auth token in the auth header in order for the action to execute and return JSON. Should this be good enough?