Django JWT send token via Angularjs - angularjs

how shall I send the token too access a view. Can I send it via POST or does it has to be via the header?
How can I send the token via header if that is necessary?

you have to send the token in the Authorization header. The token should be JWT <token>, as per documented in django jwt.
Here is the Angularjs based function I have written to show how to sign up, the code is very basic just for understanding you can write a separate service or factory, but for the sake of explaining this seems good.
$scope.registerUser = function(){
var postDict = $scope.user;
$http.post('http://127.0.0.1:8000/api/v1'+'/accounts/', postDict).success(function(data){
$scope.userRegistered = data;
var authData = {
username: data.username,
password: data.password
};
$http.post('http://127.0.0.1:8000/api-token-auth/', authData).success(function(data){
var token = data.token;
$http({
method : 'POST',
url : 'http://127.0.0.1:8000/api/v1/auth/login/',
data : authData, // pass in data as strings
headers : { "Content-Type": "application/json", "Authorization": "JWT "+data.token } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data){
console.log(data);
var userdata = { "username": data.username, "first_name": data.first_name , "token": token , "last_name": data.last_name , "email": data.email};
$window.localStorage.setItem('userdata', JSON.stringify(userdata));
$state.go('app.dashboard');
});
});
});
}
now here we have obtained the token and in the headers property of the $http.post method of the angularjs, we have used this token for login.
This is how you can use Django JWT in Angularjs , also have a look at the django jwt documentation

You have to send it through a header named Authorization with the value: Token your-token-value.
In AngularJS you can do this through the $httpProvider in the configuration of your module, for instance:
angular.module('mymodule', []).config(function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Token your-token-value';
});
After you do that, every request made with $http will have this header.

Related

Microsoft Graph API - not receiving refresh token

I'm using the below guide to setup Oauth2 for my app.
https://learn.microsoft.com/en-us/graph/auth-v2-user
this is the /authorize URL get request, which is working fine:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${clientId}&response_type=code&redirect_uri=${redirectUri}&response_mode=query&scope=offline_access%20user.read%20files.readwrite
then, i get the code from the redirectUri and POST to this URL:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Which returns a access_token and a refresh_token.
However, whenever i need to refresh the tokens, Graph API only returns a new access_token.
I'm using axios and qs:
//get new tokens
const scope = "Files.ReadWrite";
const data = qs.stringify({
client_id: clientId,
client_secret: clientSecret,
grant_type: "refresh_token",
redirect_uri: redirectUri,
scope: scope,
refresh_token: oneDriveRefreshToken
});
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
const response = await axios.post(tokenEndpoint, data, headers);
const json = response.data;
functions.logger.debug(json.access_token); //ok
functions.logger.debug(json.refresh_token); //undefined
As far as i understand, the authorization code flow along with "offline_access" scope should enable you to get a new refresh token when calling the /token endpoint
I noticed that the scope you defined in the code does not include offline_access, so it just returns you an access token with Files.ReadWrite permission. If you want to obtain an refresh token, please add offline_access to the scope.
Try to change the scope to: const scope = "Files.ReadWrite offline_access";.

AngularJS : Implementing token in $http

I am very new to angularJS.
My Backend is DRF and I have successfully implemented token.
this is my token:
{
"key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
Before I implement token in backend, it was working nice:
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
.then(function(response) {
$scope.contacts = response.data;
});
};
But, now I am not getting how can I implement this token here
Can anyone help me in this case?
Try to use this. You need to attach the token in the headers.
$http({
url : "http://127.0.0.1:8000/api/v1/contact",
method : 'GET',
headers : {
'Content-Type' : 'application/json',
'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
}).then(function(response){
$scope.contacts = response.data;
});
Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default

How can we send OAuth2.0 with axios in React js

I am working on one authentication problem where i have to implement OAuth2.0 authentication for my React App. Is there any way that i can use that authentication with Axios Promise based library???
You will have to pass your Token in the header.
See below;
const instance = axios.create({
baseURL: 'http://localhost/api/',
headers: {'Authorization': 'basic '+ token}
});
instance.get('/path')
.then(response => {
return response.data;
})
OR
Set an Authorization cookie in the browser once you get your token.
The browser will always send the Authorization cookie in each request made to the server. You won't have to pass it through Axios get/post.
UPDATE:
In order to get the access token from the oAuth server, pass the client_id, client_secret, scope and grant_type as follows;
var axios = require("axios");
axios.request({
url: "/oauth/token",
method: "post",
baseURL: "http://sample.oauth.server.com/",
auth: {
username: "myUsername", // This is the client_id
password: "myPassword" // This is the client_secret
},
data: {
"grant_type": "client_credentials",
"scope": "public"
}
}).then(respose => {
console.log(respose);
});
I am assuming that you are using grant_type = "client_credentials", if not, then based on the grant_type you use, you will have to also change the request parameters accordingly.

Angularjs $http service passing facebook access token

I'm implementing fb authentication in my SPA built using MEAN stack. While I've successfully implemented the fb authentication using facebook token passport strategy, I'm facing issues in securing API endpoints. Because for that I need to pass both the authenticated user object and access token in the $http service and I've tried passing access_token as a property of the user object and also as a header property, but I still 401 (Unauthorized error). Below is my code snippet.
Passport documentation says "Authorization: Bearer base64_access_token_string". Should the token be encoded in a base64 format? Pls help.
server code
app.get('/api/getbikes*',
passport.authenticate('facebook-token',{session: false}),
function(req,res){
if(req.user){
console.log('In getbikes api');
// console.log('req.query :',req.query);
var msg="";
ubBike
.find({cust:req.query._id})
.populate('cust','email')
.exec(function(err,bikes){
res.send(bikes);
if(err) throw err;
});
}
else
{
res.send(401);
}
});
angular code
service
this.getbikes = function(user){
var deferred = $q.defer();
$http({
method:"GET",
url:"http://localhost:3000/api/getbikes",
params: user,
headers:{
Authorization:auth.getAccesstoken()
}
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},
function failureCallback(srresponse){
$log.error("get bikes http call failed ",srresponse.data);
deferred.reject(srresponse.data);
});//$http
return deferred.promise;
};//getbikes
controller
$scope.fblogin= function(){
auth.fblogin().then(
function(response){
$scope.isAuth = auth.isAuth;
$scope.usr =auth.getResponseobj();
$scope.usr.access_token=auth.getAccesstoken();
$scope.profpic=auth.profpic;
bike.getbikes($scope.usr).then(function(response){
if (response.length ==0)
{
$location.path('/addbike');//redirect to addbike screen
}
else{
$location.path('/appoint');//else redirect to view appointment screen
}
},function(reason){
$scope.msg1 = reason;
});//getbikes
},function(reason){
$log.log("fblogin() - failure :Need to login to the application :"+reason);
})
};//fblogin
Surprisingly, when I send the header as "Authorization: Bearer access_token_string" ie the fb token as is without base64 encoding the API authentication works perfectly fine. This is contrary to the passport facebook token documentation https://github.com/drudge/passport-facebook-token

Angular $http post with custom headers

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

Resources