Reputation: 795
I'm looking to pull the current user's login name from the Okta API, but I'm usually just an HTML/CSS guy so I'm struggling. I'm currently stuck with this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery.ajax({
url: "https://harmelin.okta.com/api/v1/users/me",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
</script>
</head>
<body>
<script type="text/javascript">
document.write(data.profile.login);
</script>
</body>
I've used parts of that code in the past with other APIs but had to go a little hack on it. I know that my problem is authorization as I'm getting a 403 error. The Okta documentation gives this as a request example:
curl -v -X GET \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: SSWS ${api_token}" \
"https://${org}.okta.com/api/v1/users/me"
How do I get the authorization in my script? Will that provide me with what I need for future development (data.profile.login)?
Upvotes: 1
Views: 1619
Reputation: 11226
You should NOT include the SSWS token in requests from the browser. Anyone who reads the source of your page could use it to make modifications to your org.
If you received a 403, it's because a user is not logged in or the cookie is not being sent.
If the user is not logged in, they should log in using the okta-signin-widget, okta-auth-js, or your login page.
In your case, the cookie is not being sent, because it's a CORS request. By default, jQuery doesn't send cookies on cross domain requests. You can fix this by sending withCredentials
in your request.
After the user logs in, the following request should work:
jQuery.ajax({
url: "https://harmelin.okta.com/api/v1/users/me",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function(err){
alert(JSON.stringify(err));
}
});
Upvotes: 3
Reputation: 1390
You should add
(code not tested)
headers: {
"Authorization": "SSWS ${api_token}",
"Content-Type": "application/json",
"Accept": "application/json"
},
Upvotes: 0