0% found this document useful (0 votes)
19 views

Authentication & Authorization 2

Authentication & authorization 2 in react

Uploaded by

Marada Prudhvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Authentication & Authorization 2

Authentication & authorization 2 in react

Uploaded by

Marada Prudhvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

JWT Token

JSON Web Token is a standard used to create Access Tokens. These access tokens are
also called JWT Tokens.

The client uses these access tokens on every subsequent request to communicate with
the Server.

Note
While making HTTP Request, we have to send an access token in the HTTP Headers with
the key Authorization.

Example:

Authorization: Bearer jwt_token

1.1 Storing JWT Token in State

When we store the JWT Token in the state,On page refresh, the JWT token won't be
available
It is difficult to pass state information to every component

2. Storage Mechanisms

Client-Side Data Storage


->Storing Data on the Client

Server-Side Data Storage


->Storing Data on the Server using some kind of Database

Different types of Client-Side data storage mechanisms are:

Local Storage
Cookies
Session Storage
IndexedDB, etc.

3. Cookies

A cookie is a piece of data that is stored on the user's computer by the web
browser.

A cookie is made up of:

Name & Value


->Expires − The date the cookie will expire. If this is blank, the cookie will
expire
when the visitor quits the browser.
->Domain − The domain name of your site.
->Path − The path to the directory or web page that set the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
->Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists,
etc.
3.1 Why Cookies?
With cookies, we can set the expiry duration.
Examples:

Banking Applications - Cookies get expired in minutes


Facebook - Cookies get expired in months or years

3.2 Cookies vs Local Storage


Cookies Local
Storage
We can set an expiration for Cookies Local storage data never
expires
Cookies can store up to 4KB of data Local Storage can store up
to 5 to 10 MB of data

3.3 Third Party Package - js-cookie

JavaScript can read, create, modify, and delete the cookies.

NPM contains a js-cookie, a third-party package to manipulate cookies easily.

Installation Command:

npm install js-cookie --save

js-cookie methods are:

->Cookies.set()- It is used to set the cookie


->Cookies.get()- It is used to get the cookie
->Cookies.remove()- It is used to remove the cookie

3.3.1 Cookies.set()

Cookies.set('CookieName', 'CookieValue', {expires: DAYS});


eg:Cookies.set('ACCESS_TOKEN', 'Us1L90PXl...', {expires: 1});

Cookies.get()

It returns undefined if the cookie expires or does not exist.

Syntax:

Cookies.get('CookieName');
eg:Cookies.get('ACCESS_TOKEN');

cookies.remove()

Syntax:

Cookies.remove('CookieName');

eg:Cookies.remove('ACCESS_TOKEN');

Redirect Component vs history Methods


Use the Redirect Component when you have to stop displaying UI and navigate to a
route.
Ex: Inside Class Component - render()
In all other cases, use history.push() or history.replace()
syntax Ex: onSubmit, onClick event callback functions

Note
The Redirect component uses the history push and replace methods behinds the scene.

withRouter

The history prop will be available for only components which are directly given for
Route.

To provide history prop to other components, we can wrap it with the withRouter
function while exporting it.

Example:

import { withRouter} from 'react-router-dom'


...
export default withRouter(ComponentName)

-----------------------------------------------------------------------------------
----------------------------
E-Commerce Application
Make an Authentication Request to Login API
Handle Login API Response
On Login Success
On Login Failure
Store the JWT Token

File: src/App.js

import {BrowserRouter, Route, Switch} from 'react-router-dom'

import LoginForm from './components/LoginForm'


import Home from './components/Home'
import Products from './components/Products'
import Cart from './components/Cart'
import NotFound from './components/NotFound'

import './App.css'

const App = () => (


<BrowserRouter>
<Switch>
<Route exact path="/login" component={LoginForm} />
<Route exact path="/" component={Home} />
<Route exact path="/products" component={Products} />
<Route exact path="/cart" component={Cart} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)

export default App


###################################################################################
#####################

File: src/components/Cart/index.js

import Header from '../Header'


import './index.css'

const Cart = () => (


<>
<Header />
<div className="cart-container">
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-cart-img.png"
alt="cart"
className="cart-img"
/>
</div>
</>
)

export default Cart

###################################################################################
#######################

File: src/components/Header/index.js

import {Link, withRouter} from 'react-router-dom'

import Cookies from 'js-cookie'

import './index.css'

const Header = props => {


const {history} = props
const onClickLogout = () => {
Cookies.remove('jwt_token')
history.replace('/login')
}
return (
<nav className="nav-header">
<div className="nav-content">
<img
className="website-logo"
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
alt="website logo"
/>
<ul className="nav-menu">
<Link to="/" className="nav-link">
<li>Home</li>
</Link>
<Link to="/products" className="nav-link">
<li>Products</li>
</Link>
<Link to="/cart" className="nav-link">
<li>Cart</li>
</Link>
</ul>
<button
type="button"
className="logout-desktop-btn"
onClick={onClickLogout}
>
Logout
</button>
<button
type="button"
className="logout-mobile-btn"
onClick={onClickLogout}
>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-log-out-
img.png"
alt="logout icon"
className="logout-icon"
/>
</button>
</div>
</nav>
)
}
export default withRouter(Header)

###################################################################################
################

File: src/components/Home/index.js

import Cookies from 'js-cookie'


import {Redirect} from 'react-router-dom'
import Header from '../Header'

import './index.css'

const Home = () => {


const jwtToken = Cookies.get('jwt_token')
if (jwtToken === undefined) {
return <Redirect to="/login" />
}

return (
<>
<Header />
<div className="home-container">
<div className="home-content">
<h1 className="home-heading">Clothes That Get YOU Noticed</h1>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-home-img.png"
alt="dresses to be noticed"
className="home-mobile-img"
/>
<p className="home-description">
Fashion is part of the daily air and it does not quite help that it
changes all the time. Clothes have always been a marker of the era
and we are in a revolution. Your fashion makes you been seen and
heard that way you are. So, celebrate the seasons new and exciting
fashion in your own way.
</p>
<button type="button" className="shop-now-button">
Shop Now
</button>
</div>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-home-img.png"
alt="dresses to be noticed"
className="home-desktop-img"
/>
</div>
</>
)
}

export default Home

###################################################################################
##############

File: src/components/LoginForm/index.js

import {Component} from 'react'


import Cookies from 'js-cookie'
import './index.css'

class LoginForm extends Component {


state = {
username: '',
password: '',
showSubmitError: false,
errorMsg: '',
}

onChangeUsername = event => {


this.setState({username: event.target.value})
}

onChangePassword = event => {


this.setState({password: event.target.value})
}

onSubmitSuccess = jwtToken => {


const {history} = this.props

Cookies.set('jwt_token', jwtToken, {expires: 30})


history.replace('/')
}

onSubmitFailure = errorMsg => {


this.setState({showSubmitError: true, errorMsg})
}

submitForm = async event => {


event.preventDefault()
const {username, password} = this.state
const userDetails = {username, password}
const url = 'https://apis.ccbp.in/login'
const options = {
method: 'POST',
body: JSON.stringify(userDetails),
}
const response = await fetch(url, options)
const data = await response.json()
if (response.ok === true) {
this.onSubmitSuccess(data.jwt_token)
} else {
this.onSubmitFailure(data.error_msg)
}
}

renderPasswordField = () => {
const {password} = this.state
return (
<>
<label className="input-label" htmlFor="password">
PASSWORD
</label>
<input
type="password"
id="password"
className="password-input-filed"
value={password}
onChange={this.onChangePassword}
/>
</>
)
}

renderUsernameField = () => {
const {username} = this.state
return (
<>
<label className="input-label" htmlFor="username">
USERNAME
</label>
<input
type="text"
id="username"
className="username-input-filed"
value={username}
onChange={this.onChangeUsername}
/>
</>
)
}

render() {
const {showSubmitError, errorMsg} = this.state
return (
<div className="login-form-container">
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
className="login-website-logo-mobile-image"
alt="website logo"
/>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-login-img.png"
className="login-image"
alt="website login"
/>
<form className="form-container" onSubmit={this.submitForm}>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
className="login-website-logo-desktop-image"
alt="website logo"
/>
<div className="input-container">{this.renderUsernameField()}</div>
<div className="input-container">{this.renderPasswordField()}</div>
<button type="submit" className="login-button">
Login
</button>
{showSubmitError && <p className="error-message">*{errorMsg}</p>}
</form>
</div>
)
}
}

export default LoginForm


###################################################################################
####################

File: src/components/NotFound/index.js

import './index.css'

const NotFound = () => (


<div className="not-found-container">
<img
src="https://assets.ccbp.in/frontend/react-js/not-found-blog-img.png"
alt="not-found"
className="not-found-img"
/>
</div>
)

export default NotFound

###################################################################################
################

File: src/components/Products/index.js

import Header from '../Header'

import './index.css'

const Products = () => (


<>
<Header />
<div className="products-container">
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-products-img.png"
alt="products"
className="products-img"
/>
</div>
</>
)

export default Products

###################################################################################
##############

You might also like