Skip to content

Instantly share code, notes, and snippets.

@alenthomas
Created September 17, 2018 18:36
Show Gist options
  • Save alenthomas/c82d650136b0c9c592d17d11494a9d84 to your computer and use it in GitHub Desktop.
Save alenthomas/c82d650136b0c9c592d17d11494a9d84 to your computer and use it in GitHub Desktop.
// src/OktaAuthComponent.js
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { withAuth } from '@okta/okta-react';
export const OktaAuthComponent = withAuth(class Auth extends Component {
constructor(props) {
super(props);
this.state = { authenticated: null };
this.checkAuthentication = this.checkAuthentication.bind(this);
this.checkAuthentication();
this.login = this.login.bind(this);
}
async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
this.setState({ authenticated });
}
}
componentDidUpdate() {
this.checkAuthentication();
}
async login() {
// Redirect to '/' after login
this.props.auth.login('/');
}
render() {
if (this.state.authenticated === null) return null;
return (this.state.authenticated ?
this.props.children :
<button onClick={this.login}>Login</button>); // component which initiates login i.e invokes the okta login function
}
});
export const OktaLogout = withAuth(class Logout extends Component {
async logout() {
this.props.auth.logout();
}
render() {
this.logout()
return <Redirect to='/' />
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment