Angular 2 JWT doesnot sends Authorization Bearer Token during page reload - laravel

I am using Tymon JWT to setup the JWT Token from my Laravel application.
I have setup similar to the quick start guide and when i test using the postman, the backend successfully returns the access token.
On frontend i am using Angular2-jwt to send the request from frontend also replacing the Http module with AuthHttp from this package which is a wrapper for the Http module.
Configured the AuthModule similar to the guide:
import { NgModule } from '#angular/core';
import { Http, RequestOptions } from '#angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'token',
noJwtError : true, //<== Using this explicitely because i am using AuthHttp on every routes.
tokenGetter: (() => sessionStorage.getItem('token')),
globalHeaders: [{'Content-Type':'application/json'}],
}), http, options);
}
#NgModule({
providers: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
]
})
export class AuthModule {}
During the first load of the login page also if i have valid auth token there is no any Authorization: Bearer <token> added in the Get request. Sometimes it gets added in the Header and on some request there is no Authorization in the header.
Image1:
No Authorization added in the header even though there is valid token
Image2:
Authorization Header Added before requesting the token to the backend.
I am not sure about the addition of the header when does it adds and when does it removes from the header.
Have anyone else received this kind of issue?
If further details is required will add them.

Related

Axios not sending XSRF token with headers

I am integrating a Vue JS (Quasar framework) based SPA with API. The API is built in Laravel and is using sanctum for CSRF.
When I send a request to the sanctum endpoint https://someweburl.com/sanctum/csrf-cookie it sends the XSRF-TOKEN as cookie correctly. But when I am sending the the POST request, the X-XSRF-TOKEN is not attaching itself with the header. And I am getting a 'token mismatch' error.
The front-end is on my localhost:8080 while the API is live on a url. I do not have direct access to the Laravel project but only the API.
Following is my axios configuration
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;
const apiBaseUrl = "https://someweburl.com";
const api = axios.create({ baseURL: apiBaseUrl });
api.defaults.withCredentials = true;
Vue.prototype.$api = api;
Vue.prototype.$apiBaseURL = apiBaseUrl;
export { axios, api, apiBaseUrl }
Following is the request format that I am trying to achieve i.e A POST request after getting the CSRF
export const fetchAllEvents = async function (context, payload) {
this._vm.$api.get('/sanctum/csrf-cookie').then(response => {
this._vm.$api.post('/api/website/event/all').then(response => {
context.commit('setAllEvents', response.data.data);
}).catch(error => {
console.log(error);
})
}).catch(error => {
console.log(error);
})
}
When I check use Postman to make the POST request with X-XSRF-TOKEN added as header, i am getting the correct response. Which means the API is working correctly. But there's some issue with axios.
Any help will be appreciated.
Maybe that is because the Axios only sets the X-XSRF-TOKEN header when the front and backend have the exact origin. You mentioned you are trying with your frontend app at your localhost and the API is on the web at another URL.
See the axios GitHub repository for more information: https://github.com/axios/axios/blob/cd8989a987f994c79148bb0cacfca3379ca27414/lib/adapters/xhr.js#L179

How to integrate AWS API Gateway API Key with Axios | CORS Error

I have built an API in AWS API Gateway. I have written the endpoints to perform basic CRUD operations as well. I am making a call to those endpoints using axios from my React frontend. The APIs in turn call AWS Lambda functions to interact with DynamoDB.
Since DynamoDB contains sensitive user data, I wish to secure it with an API key.
As per the steps mentioned here and here.
Now in order to make an API call I had the following code. Please note that I have swapped in the real values with dummy values for explanation purposes.
src/config/api.js
const customHeaders = {
"X-Api-Key": "thisIsADummyStringForExplanation",
"Content-Type": "application/json",
};
const axiosInstance = axios.create({
baseURL: "https://this.is.a.dummy.base.url/v0",
headers: customHeaders,
});
const Aws_Api_Gateway_GET = (uri) => {
return axiosInstance({
method: "get",
url: `${uri}`,
timeout: 2000,
});
};
export { Aws_Api_Gateway_GET };
Following is the Code that I wrote in order to make a GET request at the API endpoint
Aws_Api_Gateway_GET("/my-resource")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
THE ISSUE
This code throws CORS Error. I can assure that I have enabled CORS on the API Gateway by selecting the Enable CORS option for each and every resource.
Following is the error
Access to XMLHttpRequest at 'https://this.is.a.dummy.base.url/v0/my-resource' from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But when I try the same using Postman, it works.
Can someone please help me get rid of the CORS Error ?
Thanks in advance.

MSAL and OAuth 2.0 - Request an authorization code programmatically

Goal is to get access token from MSAL programmatically for Cypress e2e tests.
We use V2.0 API.
According to this I first need to get the authorization code: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code
to get the access token https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-access-token
So in order to get authorization code I would need to do this request
// GET
// Line breaks for legibility only
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256
But this returns text/html so I would need to manually login to get the code.
Is there any way to progammatically to get the authorization code?
This is how I got it solved by creating a login command. The command fetches the token programatically and stores it into localStorage.
import 'cypress-localstorage-commands';
Cypress.Commands.add('login', () => {
const request = {
method: 'POST',
form: true,
url: `https://login.microsoftonline.com/${Cypress.config('tenantId')}/oauth2/v2.0/token`,
body: {
grant_type: 'client_credentials',
client_id: Cypress.config('clientId'),
client_secret: Cypress.config('clientSecret'),
scope: `${Cypress.config('clientId')}/.default`,
},
};
cy.request(request).then(response => cy.setLocalStorage('msal.idtoken', response.body.access_token));
});

Cannot includ/send jwt token using auth0/angular-jwt

I use "https://github.com/auth0/angular2-jwt" to send JWT token to my server, I can see the token when I debug http request (angular) but at the server (java) the token is not found
this is my config jwt
JwtModule.forRoot({
config: {
headerName: 'API_TOKEN',
tokenGetter: function tokenGetter() {
return localStorage.getItem('API_TOKEN');
},
whitelistedDomains: ['localhost:8092'],
// blacklistedRoutes: ['https://localhost:8092/login'],
authScheme: ''
}
}),
I added a JwtHttpInterceptor for debug my request :
#Injectable()
export class JwtHttpInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
and this is a screenshot : JWT token in header request
but server could not find this token.
When I try to add token with a chrome pluging, It work and server can find my token : token added with chrome pluging
Can you help me please?
I found the solution if it will help another person, in fact it comes from the backend, I reversed the spring security filters and my request "OPTIONS" should go through the filter CORS first
httpSecurity
.addFilter(jwtAuthenticationFilter)
.addFilterBefore(corsInputFilter, UsernamePasswordAuthenticationFilter.class) // OPTIONS REQUEST SHOULD COME HERE IN THE FIRST AND RETURN THE RESPONSE WITHOUT CONTINUE OTHERS FILTERS
.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

Nuxtjs Axios in Vuex Module CORS error

I am using Nuxtjs and built-in Vuex modules along with Nuxtjs's official axios. I'm trying to GET from my local server and it always throw CORS error.
So I made an API call to Github's public endpoint, and unsuccessfully only getting CORS error in my console.
I'm using Store actions to launch AJAX calls to server on component create lifecycle. Here is my code.
// component.vue
created () {
this.$store.dispatch('getGithubAPI')
}
// store action
async getGithubAPI ({ commit, state }) {
await this.$axios.$get('https://api.github.com/users/kaungmyatlwin', { headers: { 'Access-Control-Allow-Origin': '*' } })
.then(resp => {
console.log(resp.data)
})
}
Still no luck of getting it. Here is an error message that was thrown to console.
Failed to load https://api.github.com/users/kaungmyatlwin: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
What did I do wrong here? Or is it an error residing in async/await?
UPDATE: Strange thing is that the network call actually goes out and fetch data from server, as it can be seen in Network console from Chrome.
Ok I seem to have figured out this problem.
In nuxt.config.js, you have to put credentials: false to allow CORS wildcard.
My axios config here.
axios: {
baseURL: 'https://api.github.com',
proxyHeaders: false,
credentials: false
}
Reference: https://github.com/nuxt-community/axios-module#credentials

Resources