How to handle expired jwt token in react redux? - javascript

I'm developing the application with react js and redux. For backend i used java to create api's. So far i have created three services, login, signup, listing. I have used jwt token for listing service to secure the incformation. I have set jwt token expiration time is 10 mins in backend. Each 10 mins the jwt token will get expired and for new token i need to login again. This is what i have done in backend.
I have integrated those services in my react with redux concept. The problem which i'm getting is, each i need to go login screen for new token. I want this to be happen in background. How to do with redux?
export function handleResponse(response) {
if (response.ok) {
return response.json();
}
// If invalid jwt token the page will get redirect to login.
if (response.status === 401) {
localStorage.clear();
alert('Session expired!');
location.href = '/login';
}
}
export function loginAction(data) {
const resObject = {
username: data.username,
password: data.password,
};
return dispatch =>
fetch(`/login`, {
method: 'post',
body: JSON.stringify(resObject),
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${basicAuth.authSecret}`,
},
})
.then(handleResponse)
.then(res => dispatch(loginUser(res)));
}

Related

Axios auth request web site

I am trying to enter a website by submitting login data with axios. But each time the response.data is the site's login html page. When I want to access the site and get the data from my profile. How can I solve? how do i get the cookie token?
This is my code. Where i wrong?
await axios.post('https://namesiteweb.com/login.html',
{
'username': 'username',
'password': 'password'
}
).then(response => {
console.log(response);
}).catch(err => {
console.log(err);
});

OAuth2.0 token post request is responding 401 (invalid_client)

I am very new to the Google OAUth2.0 authentication and thus my question sounds like dumb. However, I am stuck with this problem quite a time and need your input to solve it.
I was integrating the Globus login within my app. Globus login using Google OAuth-2 protocol for authentication. According to the Globus Auth developer guide, I successfully redirect the app to their authorization service, the user can put their credential to authenticate, and the app receives the code returned from the Globus Auth server upon successful authentication. Next step is sending the code to the Token endpoint to get the access token. I used the following code:
var querystring = require('querystring');
export const logInGlobus = (payload) => {
let tokenUri = encodeURIComponent(payload.redirect_uri);
let client_id = 'out app client id'
let client_secret = 'client secret generated for authentication'
let cred = btoa(client_secret);
return axios.post('https://auth.globus.org/v2/oauth2/token',
querystring.stringify({
grant_type: 'authorization_code',
code: payload.code,
redirect_uri: tokenUri,
client_id: client_id
}),
{
headers:{
Authorization: 'Basic '+ cred,
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
return{
res: response,
success: true
}
})
.catch(err => {
return{
res: err,
success: false
}
})
}
I am getting 401 {"error":"invalid_client"} code for this post request from the server. What am I missing?
N.B: I have tried without client secret, client id, not encoding redirect URL. No luck so far>
I would really appreciate your effort if you show me some light. Thanks for your time.
====Edited====
The error from the console at the browser is attached
I solved the problem. I had to put the client secret at the body of the post request. The following code resolves my problem.
var querystring = require('querystring');
export const logInGlobus = (payload) => {
let client_id = 'app client id'
let client_secret = 'client secret generated for authentication'
return axios.post('https://auth.globus.org/v2/oauth2/token',
querystring.stringify({
grant_type: 'authorization_code',
code: payload.code,
redirect_uri: payload.redirect_uri,
client_id: client_id,
client_secret: client_secret
}),
{
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
return{
res: response,
success: true
}
})
.catch(err => {
return{
res: err,
success: false
}
})
}

How to automate the OAuth 2.0 token generation using Artillery?

I want to automate the OAuth 2.0 token automatically via javascript. Is there any way I can do that and obtain the token to use it in the artillery scrtips.
For the OAuth token generation I have below details:
Auth URL
Client ID
Scope
It is done by client authentication credentials.
Below is the sample code I am using to generate the token:
var ClientOAuth2 = require('client-oauth2')
var Auth = new ClientOAuth2({
clientId: 'ClientID',
accessTokenUri: 'https://Auth_URL/v2.0/token',
authorizationUri: 'https://Auth_URL/v2.0/authorize',
redirectUri: 'https://Auth_URL/',
scope: 'api://Scope/access_as_user'
})
Auth.owner.getToken('Username', 'password')
.then(async (user) => {
await console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
}).catch((e) => { console.log('error show',e); })
.finally( () => console.log('end'));
You can declare your custom JS files which will be triggered every time before the request:
Your YAML file can be like here:
config:
target: "https://baseUrl.com"
phases:
- duration: 60
arrivalRate: 100
processor: "./customFile.js"
scenarios:
- flow:
- post:
url: "/pathInYourApi"
headers:
Content-Type: "application/json"
Accept: application/json
json: {}
beforeRequest: "beforeRequest"
and then your customFile.js script:
module.exports = {
beforeRequest: beforeRequest,
};
function beforeRequest(requestParams, context, ee, next) {
// Call your OAuth client, and after you obtain token you can assign it to requestParams Authorization header
// eg. requestParams.headers.Authorization = `Bearer + ${token}`
return next(); // MUST be called for the scenario to continue
}

Can't set user session with Vue and Django

I have the Vue app and the Django rest framework api separately.
One on localhost:8080 (vue app) and the rest api on localhost:8000.
So, I created an APIView that is supposed to log the user in when they make a post request:
class LoginUserAPIView(APIView):
permission_classes = () # login should be accessed by anyone, no restrictions.
def post(self, request, format=None):
username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
user = UserSerializer(user)
return Response({'success': 'Logged in', 'user': user.data})
return Response({'wrong': 'username or password not correct, try again'}, status=status.HTTP_401_UNAUTHORIZED)
And I was trying to get the user session from django with axios:
login() {
this.isLoading = true;
return axios({
method: 'post',
url: 'http://localhost:8000/api/login_user',
data: {
username: this.name,
password: this.password
},
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
this.$store.commit('loginAuth', true); // setting isAuth to true in vuex store.
this.$store.commit('setUser', response.data.user); // to access the user object since I don't use django templates
this.$router.push({name: 'page'}); // redirect to random test page that requires authorization so I can see if everything went fine.
})
.catch(err => {
console.error(err);
if (err.response.status == 401) {
alert(err.response.data.wrong);
this.isLoading = false;
}
})
but I was naive and I thought this would work, so when I checked the vue app for any cookies or sessions, nothing.
How could I set user session for a separate vue app?
Thanks in advance, I apologize for my lack of knowledge.

How to send from node data to localStorage React?

node
const LocalStorage = require ('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./localStorage');
localStorage.setItem('username', user.name);
localStorage.setItem('token', user.token)
react
const author = localStorage.getItem('username')
const token = localStorage.getItem('token')
In react console.log(localStorage) // {}
P.S: maybe need send from react to node GET request?
fetch('/api', {
method: 'GET'
I Assume that you are trying to make request along with the token that you have saved in locastorage. for that you have to add Authorization headers. like
const token = localStorage.getItem('token')
fetch('https://example.com/endpoint', {
method: 'GET',
headers: {
'Authorization': token
}
})
to get the token create a specific route like
first you need to import
import jwt from 'jwt-simple';
Then
app.post('/login',function(req,res,next){
res.send({token:jwt.encode({sub:user.id,iat:timpestamp},SecretKey)});
});
where SecretKey is the key defined to encryption and here the userId with time is taken to generate the token

Categories

Resources