Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Securing Your React Application #104

Open
reboottime opened this issue May 25, 2024 · 3 comments
Open

Securing Your React Application #104

reboottime opened this issue May 25, 2024 · 3 comments

Comments

@reboottime
Copy link
Owner

reboottime commented May 25, 2024

Overview

This article covers topic - build secure react app, together some general tips


Content

@reboottime
Copy link
Owner Author

reboottime commented May 25, 2024

Common Practices

Network Perspective

  • use http only cookie for high value cookies
  • use https
  • Prevent Cross-Site Request Forgery (CSRF): Implement CSRF protection by using techniques like CSRF tokens or SameSite cookies to ensure that requests originate from your application and not from malicious sources.
  • Use Content Security Policy (CSP): Implement a Content Security Policy to restrict the sources of content that can be loaded and executed in your application, mitigating the risk of cross-site scripting and other injection attacks.


Programming Part

  • validate user input at both backend and frontend side
  • Apply proper authentication and authorization to corresponding resources and person
    • role based access control
    • not access -> not found to mix the information externally
  • Keep dependencies up to date: have regular security check and bug fix
  • Proper error handing: Handle errors gracefully and avoid revealing sensitive information in error messages. Display generic error messages to users and log detailed error information on the server-side for debugging purposes.

@reboottime
Copy link
Owner Author

reboottime commented May 25, 2024

Securing Your React Application

General tips

  • sanitize any data user provided before passing to API services
  • Add idle time management
  • be prudent when using dangerousHtml
  • Upgrade your dependencies regularly

Solutions

@reboottime
Copy link
Owner Author

reboottime commented May 25, 2024

react-idle-timer sample code

In a production app, the session validity and idle time are configurable. so you will need to derive the MAX_IDLE_TIME from the session validity time and sometime to remind user to take action.


  • UI Sample
image

If user clicks the stay logged in button, frontend makes request to backend side to extend the session time.



  • Code sample
  const [showIdleDialog, setShowIdleDialog] = useState(false);

  const { start, reset } = useIdleTimer({
    startManually: true,
    timeout: MAX_IDLE_TIME,
    onIdle: () => {
      setShowIdleDialog(true);
    });

  // Apply your logic to start/rset the timer programatically 

import { useEffect, useRef, useState } from 'react';

import Button from './ui/button';
import Dialog, { DialogContent, DialogFooter, DialogTitle } from './ui/dialog';

const IdleDialog = ({ onStayLoggedIn, onLogout }: IdleDialogProps) => {
  const timerRef = useRef<ReturnType<typeof setInterval> | undefined>();
  const [remainingTime, setRemainingTime] = useState(60);

  useEffect(() => {
    timerRef.current = setInterval(() => {
      setRemainingTime((prev) => {
        const nextTime = prev - 1;

        if (nextTime <= 0) {
          clearInterval(timerRef.current);
          onLogout();
        }

        return nextTime;
      });
    }, 1000);

    return () => {
      clearInterval(timerRef.current);
    };
  }, [onLogout]);

  return (
    <Dialog open>
      <DialogContent className='border border-brand'>
        <DialogTitle>Reminder</DialogTitle>
        <p className='text-dark mb-6'>
          You have been inactive for a while. To secure your data, you will be
          logged out in{' '}
          <span className='font-bold text-xl text-brand'>{remainingTime}</span>{' '}
          seconds.
        </p>
        <DialogFooter className='flex justify-end'>
          <Button onClick={onLogout} variant='outline'>
            Logout
          </Button>
          <Button
            onClick={() => {
              onStayLoggedIn();
              clearTimeout(timerRef.current);
              setRemainingTime(60);
            }}
          >
            Stay Logged In
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default IdleDialog;

interface IdleDialogProps {
  onLogout: () => void;
  onStayLoggedIn: () => void;
}

@reboottime reboottime changed the title Security in React App Securing Your React Application May 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant