My login function consists of a http request (an irrelevant one just for the check) with the entered credentials. This way I can resolve the request or get a rejection which I handle by not pushing the next component with the NavController onto the stack.
On logout, the credentials, which are saved in the Ionic Storage, are deleted. Now starts the problem: Any credentials that are saved now in the storage seems not to be used by the login request as the request doesn't throw an Auth exception. Only after clearing the Browser cache it works again.
This all happened by serving the app in a web browser and on the phone.
How is it possible to clear the App cache (not only the View/Component cache) with Ionic 2 to prevent this behaviour? There is no documentation or question concerning this problem existent at the moment.
Auth Service:
#Injectable()
export class AuthService {
HAS_LOGGED_IN = 'hasLoggedIn';
constructor(private storage: Storage) {
// this.rest = rest;
console.log('auth');
}
setCredentials(credentials) {
this.storage.set('username', credentials.username);
this.storage.set('password', credentials.password);
}
logout(): void {
this.storage.remove('username');
this.storage.remove('password');
this.storage.remove(this.HAS_LOGGED_IN);
}
hasLoggedIn() {
return this.storage.get(this.HAS_LOGGED_IN).then( value => {
console.log('hasLoggedIN value: ' + value);
return value === true;
});
}
}
Login Component:
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
model: any;
HAS_LOGGED_IN: string = 'hasLoggedIn';
constructor(private navCtrl: NavController,
private viewCtrl: ViewController,
private auth: AuthService,
private toastCtrl: ToastController,
private rest: RestService,
private storage: Storage) {
}
ionViewDidLoad() {
this.model = {};
}
ionViewWillEnter() {
this.viewCtrl.showBackButton(false);
this.displayTab(false);
}
login() {
console.log(this.model);
console.log('login() claled');
this.displayTab(true);
this.auth.setCredentials(this.model);
this.rest.getEntryPoint().then(data => {
console.log(data);
this.storage.set(this.HAS_LOGGED_IN, true);
this.navCtrl.push(OverviewPage);
}).catch(err => {
this.storage.set(this.HAS_LOGGED_IN, false);
console.log('Error:');
console.log(err);
this.navCtrl.push(LoginPage).then(response => {
console.log(response);
console.log(this.navCtrl);
console.log('pushed login 1');
});
});
}
validate(items: boolean) {
if (items) {
let toast = this.toastCtrl.create({
message: 'Passwort und Benutzername sind zwingend',
duration: 3000,
position: 'bottom',
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
}
private displayTab(display: boolean) {
let elements = document.querySelectorAll('.tabbar');
if (elements != null) {
Object.keys(elements).map((key) => {
elements[key].style.transform = display ? 'translateY(0)' : 'translateY(70px)';
});
}
}
}
Intercepting Http methods (this service is used in another service that makes the actual Rest calls):
#Injectable()
export class HttpInterceptorService {
constructor(#Inject(Http) private http: Http, private storage: Storage) {
this.http = http;
console.log('interceptor');
}
get(url) {
return new Promise((resolve, reject) => {
let headers = new Headers();
this.createAuthorizationHeader(headers).then(() => {
return this.http.get(url, {
headers: headers,
}).subscribe(data => {
resolve(data.json());
}, err => {
reject(err);
});
});
});
}
put(url: string, attributes?) {
return new Promise((resolve, reject) => {
let headers = new Headers();
this.createAuthorizationHeader(headers).then(() => {
return this.http.put(url, (attributes) ? attributes : {}, {
headers: headers,
}).subscribe(data => {
resolve(data.json());
}, err => {
reject(err);
});
});
});
}
post(url: string, data) {
return new Promise((resolve, reject) => {
let headers = new Headers();
this.createAuthorizationHeader(headers).then(() => {
return this.http.post(url, data, {
headers: headers,
}).subscribe(output => {
resolve(output.json());
}, err => {
reject(err);
});
});
});
}
private createAuthorizationHeader(headers: Headers): Promise<void> {
console.log('creating auth header');
return new Promise(resolve => {
this.storage.get('username')
.then( username => {
this.storage.get('password')
.then( password => {
headers.append('Authorization', 'Basic ' +
btoa(username + ':' + password));
resolve();
});
});
});
}
}
The other components are using hasLoggedIn() function to check if we are logged in or not when switching back to the App. If not logged in anymore (storage cleaned in any way) we get back to the LoginPage component.
The problem was a session header in the response that I somehow didn't see beforehand.
My solution is a simple Cookies clearing:
window.cookies.clear(function() {});
Related
I'm building a website witch has some protected routes that I want to prevent non-authenticated users from accessing it, So I'm using Laravel Sanctum for that purpose. I was testing this using postman, but now I want to actually use it in production from backend, So how I suppose to do that token that was generated after login!
Thanks in advance.
I think the answer is late, but it may be useful to someone else
You will set your login routes
// Login Route
Route::middleware('guest')->group(function () {
Route::post('/login', LoginAction::class)->name('auth.login');
});
// Logout Route
Route::middleware('auth:sanctum')->group(function () {
Route::post('/logout', LogoutAction::class)->name('auth.logout');
});
public function __invoke(AuthRequest $request)
{
$username = $request->input('username');
$password = $request->input('password');
$remember = $request->input('remember');
// I use filter_var to know username is email or just the regular username
$field = filter_var($username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
// User::where('username', $username)->first();
// User::where('email', $username)->first();
$user = User::where($field, $username)->first();
if (
!$user || !Hash::check($password, $user->password)
|| !Auth::attempt(
[
$field => $username,
'password' => $password
],
$remember
)
) {
// Return Error Message
return $this->error(['message' => trans('auth.failed')], Response::HTTP_UNAUTHORIZED);
}
// After Check Useranme And Password Create Token
$token = $user->createToken($request->device)->plainTextToken;
// Return Success Message With Token
return $this->success(['message' => trans('auth.login', ['user' => $user->username]), 'token' => $token, 'user' => $user]);
in vuex Actions
export const loginAction = ({ commit }, userInfo) => {
let urlParams = new URLSearchParams(window.location.search);
return new Promise((resolve, reject) => {
login(userInfo)
.then((response) => {
if (response.success) {
commit("SET_LOGIN_USER", response.payload.user);
// Set Token Mutaion
commit("SET_TOKEN", response.payload.token);
// Notify User for success logged in
Notify.create({
type: "positive",
message: `welcome ${response.payload.user.username}`,
});
// Redirect to dashboard
router.push(
urlParams.get("redirect") || { name: "dashboard" }
);
}
resolve(response);
})
.catch((error) => {
// For any error remove any auth user details and notify him
Notify.create({
type: "negative",
message: `${error.response?.data.payload}`,
});
commit("REMOVE_AUTH_DETAILS");
reject(error);
});
});
};
in vuex mutations 3 methods
// Helpers Fuctions
import { setLoginUser, setToken, removeToken, removeLoginUser } from '../../../utils/auth';
export const SET_LOGIN_USER = (state, user) => {
state.loginUser = user
setLoginUser(user)
}
export const SET_TOKEN = (state, token) => {
state.token = token
setToken(token)
}
export const REMOVE_AUTH_DETAILS = (state) => {
state.loginUser = null
state.token = null
removeLoginUser()
removeToken()
}
My Helper Functions
// I use Quasar Framework But you can use any cookie package like js-cookie
import { Cookies } from "quasar";
const TokenName = "TOKEN";
const LoginUser = "LOGIN_USER";
export function setToken(token) {
return Cookies.set(TokenName, token);
}
export function getToken() {
return Cookies.get(TokenName);
}
export function removeToken() {
return Cookies.remove(TokenName);
}
export function setLoginUser(loginUser) {
return Cookies.set(LoginUser, JSON.stringify(loginUser));
}
export function getLoginUser() {
return Cookies.get(LoginUser);
}
export function removeLoginUser() {
return Cookies.remove(LoginUser);
}
I use Vue js for frontend and axios for making requests
in axios file request.js
// It's helper function to get token from cookie
import { getToken } from "./auth";
import router from "../router";
import store from "../store";
import axios from "axios";
// Create axios instance
const service = axios.create({
baseURL: "/api/v1/",
timeout: 10000 // Request timeout
});
// Request intercepter
service.interceptors.request.use(
config => {
if (getToken()) {
config.headers["Authorization"] = "Bearer " + getToken(); // Set Token
}
return config;
},
error => {
// Do something with request error
console.log("error-axios", error); // for debug
Promise.reject(error);
}
);
// response pre-processing
service.interceptors.response.use(
response => {
return response.data;
},
error => {
// remove auth user informations from cookies and return to login page if unauthorized
if ([401].includes(error.response.status)) {
store.commit('auth/REMOVE_AUTH_DETAILS')
router.push({ name: "login" });
}
return Promise.reject(error);
}
);
export default service;
// Logout Fuction in controller or action
public function __invoke(Request $request)
{
if(! $request->user()) {
return $this->error(['message' => trans('auth.no_auth_user')]);
}
// Remove Token
$request->user()->tokens()->delete();
return $this->success([
'message' => trans('auth.logout', ['user' => auth()->user()->username])
], Response::HTTP_OK);
}
// Logout mutation (vuex)
export const logoutAction = ({ commit }) => {
return new Promise((resolve, reject) => {
logout()
.then(() => {
Notify.create({
type: "negative",
message: `see you later ${getLoginUser().username}`,
});
commit("REMOVE_AUTH_DETAILS");
router.push({ name: "login" });
resolve();
})
.catch((error) => {
router.push({ name: "login" });
commit("REMOVE_AUTH_DETAILS");
reject(error);
});
});
};
Any other help I will not be late
So we're creating a React-Native app using Apollo and GraphQL. I'm using JWT based authentication(when user logs in both an activeToken and refreshToken is created), and want to implement a flow where the token gets refreshed automatically when the server notices it's been expired.
The Apollo Docs for Apollo-Link-Error provides a good starting point to catch the error from the ApolloClient:
onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case 'UNAUTHENTICATED':
// error code is set to UNAUTHENTICATED
// when AuthenticationError thrown in resolver
// modify the operation context with a new token
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: getNewToken(),
},
});
// retry the request, returning the new observable
return forward(operation);
}
}
}
})
However, I am really struggling to figure out how to implement getNewToken().
My GraphQL endpoint has the resolver to create new tokens, but I can't call it from Apollo-Link-Error right?
So how do you refresh the token if the Token is created in the GraphQL endpoint that your Apollo Client will connect to?
The example given in the the Apollo Error Link documentation is a good starting point but assumes that the getNewToken() operation is synchronous.
In your case, you have to hit your GraphQL endpoint to retrieve a new access token. This is an asynchronous operation and you have to use the fromPromise utility function from the apollo-link package to transform your Promise to an Observable.
import React from "react";
import { AppRegistry } from 'react-native';
import { onError } from "apollo-link-error";
import { fromPromise, ApolloLink } from "apollo-link";
import { ApolloClient } from "apollo-client";
let apolloClient;
const getNewToken = () => {
return apolloClient.query({ query: GET_TOKEN_QUERY }).then((response) => {
// extract your accessToken from your response data and return it
const { accessToken } = response.data;
return accessToken;
});
};
const errorLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case "UNAUTHENTICATED":
return fromPromise(
getNewToken().catch((error) => {
// Handle token refresh errors e.g clear stored tokens, redirect to login
return;
})
)
.filter((value) => Boolean(value))
.flatMap((accessToken) => {
const oldHeaders = operation.getContext().headers;
// modify the operation context with a new token
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
// retry the request, returning the new observable
return forward(operation);
});
}
}
}
}
);
apolloClient = new ApolloClient({
link: ApolloLink.from([errorLink, authLink, httpLink]),
});
const App = () => (
<ApolloProvider client={apolloClient}>
<MyRootComponent />
</ApolloProvider>
);
AppRegistry.registerComponent('MyApplication', () => App);
You can stop at the above implementation which worked correctly until two or more requests failed concurrently. So, to handle concurrent requests failure on token expiration, have a look at this post.
Update - Jan 2022
you can see basic React JWT Authentication Setup from: https://github.com/bilguun-zorigt/React-GraphQL-JWT-Authentication-Example
I've also added the safety points to consider when setting up authentication on both the frontend and backend on the Readme section of the repository. (XSS attack, csrf attack etc...)
Original answer - Dec 2021
My solution:
Works with concurrent requests (by using single promise for all requests)
Doesn't wait for error to happen
Used second client for refresh mutation
import { setContext } from '#apollo/client/link/context';
async function getRefreshedAccessTokenPromise() {
try {
const { data } = await apolloClientAuth.mutate({ mutation: REFRESH })
// maybe dispatch result to redux or something
return data.refreshToken.token
} catch (error) {
// logout, show alert or something
return error
}
}
let pendingAccessTokenPromise = null
export function getAccessTokenPromise() {
const authTokenState = reduxStoreMain.getState().authToken
const currentNumericDate = Math.round(Date.now() / 1000)
if (authTokenState && authTokenState.token && authTokenState.payload &&
currentNumericDate + 1 * 60 <= authTokenState.payload.exp) {
//if (currentNumericDate + 3 * 60 >= authTokenState.payload.exp) getRefreshedAccessTokenPromise()
return new Promise(resolve => resolve(authTokenState.token))
}
if (!pendingAccessTokenPromise) pendingAccessTokenPromise = getRefreshedAccessTokenPromise().finally(() => pendingAccessTokenPromise = null)
return pendingAccessTokenPromise
}
export const linkTokenHeader = setContext(async (_, { headers }) => {
const accessToken = await getAccessTokenPromise()
return {
headers: {
...headers,
Authorization: accessToken ? `JWT ${accessToken}` : '',
}
}
})
export const apolloClientMain = new ApolloClient({
link: ApolloLink.from([
linkError,
linkTokenHeader,
linkMain
]),
cache: inMemoryCache
});
If you are using JWT, you should be able to detect when your JWT token is about to expire or if it is already expired.
Therefore, you do not need to make a request that will always fail with 401 unauthorized.
You can simplify the implementation this way:
const REFRESH_TOKEN_LEGROOM = 5 * 60
export function getTokenState(token?: string | null) {
if (!token) {
return { valid: false, needRefresh: true }
}
const decoded = decode(token)
if (!decoded) {
return { valid: false, needRefresh: true }
} else if (decoded.exp && (timestamp() + REFRESH_TOKEN_LEGROOM) > decoded.exp) {
return { valid: true, needRefresh: true }
} else {
return { valid: true, needRefresh: false }
}
}
export let apolloClient : ApolloClient<NormalizedCacheObject>
const refreshAuthToken = async () => {
return apolloClient.mutate({
mutation: gql```
query refreshAuthToken {
refreshAuthToken {
value
}```,
}).then((res) => {
const newAccessToken = res.data?.refreshAuthToken?.value
localStorage.setString('accessToken', newAccessToken);
return newAccessToken
})
}
const apolloHttpLink = createHttpLink({
uri: Config.graphqlUrl
})
const apolloAuthLink = setContext(async (request, { headers }) => {
// set token as refreshToken for refreshing token request
if (request.operationName === 'refreshAuthToken') {
let refreshToken = localStorage.getString("refreshToken")
if (refreshToken) {
return {
headers: {
...headers,
authorization: `Bearer ${refreshToken}`,
}
}
} else {
return { headers }
}
}
let token = localStorage.getString("accessToken")
const tokenState = getTokenState(token)
if (token && tokenState.needRefresh) {
const refreshPromise = refreshAuthToken()
if (tokenState.valid === false) {
token = await refreshPromise
}
}
if (token) {
return {
headers: {
...headers,
authorization: `Bearer ${token}`,
}
}
} else {
return { headers }
}
})
apolloClient = new ApolloClient({
link: apolloAuthLink.concat(apolloHttpLink),
cache: new InMemoryCache()
})
The advantage of this implementation:
If the access token is about to expire (REFRESH_TOKEN_LEGROOM), it will request a refresh token without stopping the current query. Which should be invisible to your user
If the access token is already expired, it will refresh the token and wait for the response to update it. Much faster than waiting for the error back
The disadvantage:
If you make many requests at once, it may request several times a refresh. You can easily protect against it by waiting a global promise for example. But you will have to implement a proper race condition check if you want to guaranty only one refresh.
after checking this topic and some others very good on internet, my code worked with the following solution
ApolloClient,
NormalizedCacheObject,
gql,
createHttpLink,
InMemoryCache,
} from '#apollo/client';
import { setContext } from '#apollo/client/link/context';
import jwt_decode, { JwtPayload } from 'jwt-decode';
import {
getStorageData,
setStorageData,
STORAGE_CONTANTS,
} from '../utils/local';
export function isRefreshNeeded(token?: string | null) {
if (!token) {
return { valid: false, needRefresh: true };
}
const decoded = jwt_decode<JwtPayload>(token);
if (!decoded) {
return { valid: false, needRefresh: true };
}
if (decoded.exp && Date.now() >= decoded.exp * 1000) {
return { valid: false, needRefresh: true };
}
return { valid: true, needRefresh: false };
}
export let client: ApolloClient<NormalizedCacheObject>;
const refreshAuthToken = async () => {
const refreshToken = getStorageData(STORAGE_CONTANTS.REFRESHTOKEN);
const newToken = await client
.mutate({
mutation: gql`
mutation RefreshToken($refreshAccessTokenRefreshToken: String!) {
refreshAccessToken(refreshToken: $refreshAccessTokenRefreshToken) {
accessToken
status
}
}
`,
variables: { refreshAccessTokenRefreshToken: refreshToken },
})
.then(res => {
const newAccessToken = res.data?.refreshAccessToken?.accessToken;
setStorageData(STORAGE_CONTANTS.AUTHTOKEN, newAccessToken, true);
return newAccessToken;
});
return newToken;
};
const apolloHttpLink = createHttpLink({
uri: process.env.REACT_APP_API_URL,
});
const apolloAuthLink = setContext(async (request, { headers }) => {
if (request.operationName !== 'RefreshToken') {
let token = getStorageData(STORAGE_CONTANTS.AUTHTOKEN);
const shouldRefresh = isRefreshNeeded(token);
if (token && shouldRefresh.needRefresh) {
const refreshPromise = await refreshAuthToken();
if (shouldRefresh.valid === false) {
token = await refreshPromise;
}
}
if (token) {
return {
headers: {
...headers,
authorization: `${token}`,
},
};
}
return { headers };
}
return { headers };
});
client = new ApolloClient({
link: apolloAuthLink.concat(apolloHttpLink),
cache: new InMemoryCache(),
});
A much simpler solution is using RetryLink. retryIf supports async operations so one could do something like this:
class GraphQLClient {
constructor() {
const httpLink = new HttpLink({ uri: '<graphql-endpoint>', fetch: fetch })
const authLink = setContext((_, { headers }) => this._getAuthHeaders(headers))
const retryLink = new RetryLink({
delay: { initial: 300, max: Infinity, jitter: false },
attempts: {
max: 3,
retryIf: (error, operation) => this._handleRetry(error, operation)
}})
this.client = new ApolloClient({
link: ApolloLink.from([ authLink, retryLink, httpLink ]),
cache: new InMemoryCache()
})
}
async _handleRetry(error, operation) {
let requiresRetry = false
if (error.statusCode === 401) {
requiresRetry = true
if (!this.refreshingToken) {
this.refreshingToken = true
await this.requestNewAccessToken()
operation.setContext(({ headers = {} }) => this._getAuthHeaders(headers))
this.refreshingToken = false
}
}
return requiresRetry
}
async requestNewAccessToken() {
// get new access token
}
_getAuthHeaders(headers) {
// return headers
}
}
Here is my code
handleLogin = async()=> {
const { navigation } = this.props;
const errors = [];
Keyboard.dismiss();
this.setState({ loading: true });
if(this.state.email!=''){
if(this.state.password!=''){
fetch('http://192.168.1.10:8000/api/login',{
method:'post',
headers:{
'Content-Type':'application/json',
'Accept': 'application/json'
},
body:JSON.stringify({
"email":this.state.email,
"password":this.state.password
})
})
.then((response)=> response.json())
.then((res)=>{
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
if(this.state.store==='{"error":"Unauthorised"}'){
Alert.alert("Error", "These credentials do not match our records");
}
else {
Alert.alert("Success","You have succesfuly login",
[
{
text: 'Continue', onPress: () => {
Actions.NavigationCalling();
}
}
],
{ cancelable: false })
}
}).catch((error)=>{
console.error(error);
});
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert Password")
}
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert email")
}
var store=JSON.stringify(res)
Im storing data in store variable that print output like this
{"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YjYzNTY4NjNkNmYxNzBhYjdlYjVmNWRiN2MxNWU1NTUzNDc3OWUyZjM5Mjc5NWU4ODMzMjM3NDU1Y2Q3ODg1YzYzZTc0NDg2MmNjYzk2In0.eyJhdWQiOiIxIiwianRpIjoiOThiNjM1Njg2M2Q2ZjE3MGFiN2ViNWY1ZGI3YzE1ZTU1NTM0Nzc5ZTJmMzkyNzk1ZTg4MzMyMzc0NTVjZDc4ODVjNjNlNzQ0ODYyY2NjOTYiLCJpYXQiOjE1ODA5MzA2MzYsIm5iZiI6MTU4MDkzMDYzNiwiZXhwIjoxNjEyNTUzMDM2LCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.A1NZcxICOu8mudwrIrozG5FYiQxWyz1O8LcHFcaOvgXUlTkgUIuGuwxif74goMwCLkWrm3wIwZSKwMAxCAk35Ao9VZEsV3uOlelWtsjJY7u-o00baCUl3dZWJeBHLLfSODM719Oinrfepp5VGaGZ4r--rMqMnNljVEoUP8GuM0l_7rY-SA7dhXkj4a8TwogkZOzf1_0ZvgNYmM30Z_CU0umM72Iqcys-URnzb80HONI4_cVcYExqmU94UqhNsNJ9aMIDXR4WdMGzDBzhRat_E75u7Rbt67UKUbbwALv3J1qhGRb-kkE_DGR3DyAxlcNvMy21CR4b4obDE4e96GYb-7R7fLw0PiVtiyFTgLeL2Ldvw4YV8_v2TwF5zLgkh0VCqfjUTIbAir9ytjDBPDzXFy7G4mAR6qJYNPSHtgwzBcMuS2B4FWZruWg-0QbHiBFFQrDGISaf5jUTSCmiSbpd3eTKAhiifBE6eGNnzErlsG1WAn8L7zK233l1b7qDSoahIrK4PTllgsdEzFtI4sXpy_9mEbRmGmEjOTXZcUyvkFm6aajXrRwWGrhSMFIeFqRd2BNTnrh2Igwl9x7Dcj89VgXKGXyh-hP4ESwT5yHAynNhVfhaXAu1kdnkzhwzk5cDlKlYawvX02g83THN6UAElj2bttIutM-fZ1ViLIOA98k"}}
But i want to store just token in new state and pass to other screen
how can i get only token from json object and store into newstate and pass into new screen
Thanks in advance I'm new in the React native
You can access the token by doing res.success.token or you can map the json response to an object.
.then((res)=>{
var token = res.success.token // did you try doing this?
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
....
And to pass the token to another screen you can use the screen props or use redux, however, i would set it in a static variable to be accessed globally by all the screens.
I am working on a react native app that does pretty much the same that you are trying to do, i created a class called ApiService that has the following function:
static async post(url: string, payload?: object, headers?: HeadersInit_): Promise<ApiResponse> {
return await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
}).then(r => r.json().then(o => {
var mapper = new ApiResponse();
mapper.success = o.success;
mapper.result = o.success ? JSON.stringify(o.result) : o.error;
return mapper;
})).then(response => {
if (response.success)
return response;
throw ApiError(response);
});
}
The ApiResponse class looks like this:
class ApiResponse {
public success: boolean;
public result: string;
}
To access the auth token globally, i am setting the token in a static variable in a class that can be accessed everywhere.
class AbstractService {
private static sessionToken: string;
public static setSessionToken(value: string): void {
AbstractService.sessionToken = value;
}
public static getSessionToken(value: string): string {
return AbstractService.sessionToken;
}
If you want to store the token to be reused, you can use react-native-secure-key-store
Currently, my Apollo Server(running on HapiJS) returns HTTP 200 for every request, including failed ones.
I would like the GraphQL server to return HTTP 4xx for unsuccessful requests. The primary reason for it is that I want to set up monitoring for my ELB.
I know that Apollo Server has an engine platform, but I want to implement it using my current infrastructure.
Any ideas of how I could accomplish that? I tried to capture 'onPreResponse' event for my HapiJS server but I couldn't modify status code there.
After reading this answer. Here is a solution by modifying the hapijs plugin graphqlHapi of hapiApollo.ts file.
server.ts:
import { makeExecutableSchema } from 'apollo-server';
import { ApolloServer, gql } from 'apollo-server-hapi';
import Hapi from 'hapi';
import { graphqlHapi } from './hapiApollo';
const typeDefs = gql`
type Query {
_: String
}
`;
const resolvers = {
Query: {
_: () => {
throw new Error('some error');
},
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const port = 3000;
async function StartServer() {
const app = new Hapi.Server({ port });
graphqlHapi.register(app, { path: '/graphql', graphqlOptions: { schema } });
app.ext('onPreResponse', (request: any, h: any) => {
const response = request.response;
if (!response.isBoom) {
return h.continue;
}
return h.response({ message: response.message }).code(400);
});
await app.start();
}
StartServer()
.then(() => {
console.log(`apollo server is listening on http://localhost:${port}/graphql`);
})
.catch((error) => console.log(error));
hapiApollo.ts:
import Boom from 'boom';
import { Server, Request, RouteOptions } from 'hapi';
import { GraphQLOptions, runHttpQuery, convertNodeHttpToRequest } from 'apollo-server-core';
import { ValueOrPromise } from 'apollo-server-types';
export interface IRegister {
(server: Server, options: any, next?: Function): void;
}
export interface IPlugin {
name: string;
version?: string;
register: IRegister;
}
export interface HapiOptionsFunction {
(request?: Request): ValueOrPromise<GraphQLOptions>;
}
export interface HapiPluginOptions {
path: string;
vhost?: string;
route?: RouteOptions;
graphqlOptions: GraphQLOptions | HapiOptionsFunction;
}
const graphqlHapi: IPlugin = {
name: 'graphql',
register: (server: Server, options: HapiPluginOptions, next?: Function) => {
if (!options || !options.graphqlOptions) {
throw new Error('Apollo Server requires options.');
}
server.route({
method: ['GET', 'POST'],
path: options.path || '/graphql',
vhost: options.vhost || undefined,
options: options.route || {},
handler: async (request, h) => {
try {
const { graphqlResponse, responseInit } = await runHttpQuery([request, h], {
method: request.method.toUpperCase(),
options: options.graphqlOptions,
query:
request.method === 'post'
? // TODO type payload as string or Record
(request.payload as any)
: request.query,
request: convertNodeHttpToRequest(request.raw.req),
});
// add our custom error handle logic
const graphqlResponseObj = JSON.parse(graphqlResponse);
if (graphqlResponseObj.errors && graphqlResponseObj.errors.length) {
throw new Error(graphqlResponseObj.errors[0].message);
}
const response = h.response(graphqlResponse);
Object.keys(responseInit.headers as any).forEach((key) =>
response.header(key, (responseInit.headers as any)[key]),
);
return response;
} catch (error) {
// handle our custom error
if (!error.name) {
throw Boom.badRequest(error.message);
}
if ('HttpQueryError' !== error.name) {
throw Boom.boomify(error);
}
if (true === error.isGraphQLError) {
const response = h.response(error.message);
response.code(error.statusCode);
response.type('application/json');
return response;
}
const err = new Boom(error.message, { statusCode: error.statusCode });
if (error.headers) {
Object.keys(error.headers).forEach((header) => {
err.output.headers[header] = error.headers[header];
});
}
// Boom hides the error when status code is 500
err.output.payload.message = error.message;
throw err;
}
},
});
if (next) {
next();
}
},
};
export { graphqlHapi };
Now, when the GraphQL resolver throws an error, the client-side will receive our custom response with Http status code 400 instead of 200 status code with GraphQL errors response.
General from the browser:
Request URL: http://localhost:3000/graphql
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
The response body is: {"message":"some error"}
Trying to make Login feature using angular-2 where I have used one login component, authservice, logingard with canActive.
While following example from angular2 document, I don't get value of loggedin in guard file and it asks every time for login
Posting sample code here
AuthService
export class AuthService {
loggedIn: boolean = false;
isLoggedIn() {
return this.loggedIn;
}
login(credentials) {
let user = JSON.stringify(credentials);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this._apiUrl, user, options)
.map(res => res.json())
.map((res) => {
this.loggedIn = true;
}
return res;
});
}}
Loggedin Guard
export class LoggedInGuard implements CanActivate {
constructor(private _auth: AuthService, private _router: Router) {}
canActivate() {
//Get problem here. Everytime this comes false
if(this._auth.isLoggedIn()) { return true; }
this._router.navigate(['login']);
}
}
login component
export class LoginComponent {
constructor(private userService: AuthService, private router: Router) {}
onSubmit(email, password) {
this.userService.login(email, password).subscribe((result) => {
if (result) {
this.router.navigate(['']);
}
});
}
}
Btw, following example of
https://medium.com/#blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.723a4ssji
without localstorage