├── .gitignore ├── Dockerfile ├── LICENSE.md ├── k8 ├── deployment.yaml ├── secret.yaml └── service.yaml ├── mvnw ├── mvnw.cmd ├── pom.xml ├── readme.md ├── src ├── main │ ├── java │ │ └── io │ │ │ └── thepro │ │ │ └── apiservice │ │ │ ├── APIServiceApplication.java │ │ │ ├── config │ │ │ ├── FirebaseConfig.java │ │ │ └── JacksonConfig.java │ │ │ ├── controllers │ │ │ ├── ProtectedController.java │ │ │ ├── PublicController.java │ │ │ ├── SellerController.java │ │ │ └── SuperAdminController.java │ │ │ └── security │ │ │ ├── CookieService.java │ │ │ ├── SecurityConfig.java │ │ │ ├── SecurityFilter.java │ │ │ ├── SecurityService.java │ │ │ ├── SessionController.java │ │ │ ├── models │ │ │ ├── CookieProperties.java │ │ │ ├── Credentials.java │ │ │ ├── FirebaseProperties.java │ │ │ ├── SecurityProperties.java │ │ │ └── User.java │ │ │ ├── roles │ │ │ ├── IsSeller.java │ │ │ ├── IsSuper.java │ │ │ ├── RoleConstants.java │ │ │ ├── RoleController.java │ │ │ ├── RoleService.java │ │ │ └── RoleServiceImpl.java │ │ │ └── test │ │ │ ├── TestAuthController.java │ │ │ ├── TestAuthService.java │ │ │ └── TestUser.java │ └── resources │ │ ├── application.yaml │ │ ├── data │ │ └── test_users.json │ │ └── readme.md └── test │ └── java │ └── io │ └── thepro │ └── apiservice │ └── ApiServiceApplicationTests.java ├── ui-client-side-session-demo ├── .gitignore ├── README.md ├── jsconfig.json ├── package.json ├── public │ └── favicon.ico ├── screenshots │ ├── loggedin.png │ ├── loggedin_seller.png │ └── loggedout.png ├── src │ ├── components │ │ ├── data │ │ │ └── demo.js │ │ ├── navbar.js │ │ ├── rolemanager │ │ │ └── rolemanager.js │ │ └── roles │ │ │ └── roles.js │ ├── config │ │ └── firebase-config.js │ ├── contexts │ │ ├── auth.reducer.js │ │ └── useAuth.js │ └── pages │ │ ├── _app.js │ │ └── index.js └── styles.css └── ui-server-side-session-demo ├── .env.sample ├── .gitignore ├── README.md ├── cypress.json ├── cypress ├── fixtures │ └── test-users.js ├── helpers │ └── index.js ├── integration │ └── examples │ │ └── auth.spec.js ├── plugins │ └── index.js └── support │ ├── commands.js │ └── index.js ├── jsconfig.json ├── package.json ├── public ├── favicon.ico └── vercel.svg ├── screenshots ├── cypress_auth_test.gif └── screenshot.png └── src ├── components └── auth │ ├── firebase.auth.js │ ├── google.svg.js │ ├── login.js │ └── public-pages.js ├── config └── firebase.config.js ├── contexts └── useAuth.js ├── pages ├── _app.js ├── index.js └── profile.js └── styles └── globals.css /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /node_modules/ 3 | .project 4 | .classpath 5 | /.settings 6 | /src/main/resources/firebase-server-config.json 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:15 2 | VOLUME /tmp 3 | COPY target/firebase-api-service-0.0.1-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] 6 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Gladius Thayalarajan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /k8/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: firebase-middleware-deployment 5 | labels: 6 | app: firebase-middleware 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: firebase-middleware 12 | template: 13 | metadata: 14 | labels: 15 | app: firebase-middleware 16 | spec: 17 | containers: 18 | - name: firebase-middleware 19 | image: firebase-middleware:latest 20 | env: 21 | - name: GOOGLE_APPLICATION_CREDENTIALS 22 | value: "/app/thepro-firebase-config.json" 23 | ports: 24 | - containerPort: 8080 25 | volumeMounts: 26 | - name: config-volume 27 | mountPath: /app/firebase-service-account.json 28 | volumes: 29 | - name: firebase-config-volume 30 | secret: 31 | secretName: firebase-admin-config 32 | -------------------------------------------------------------------------------- /k8/secret.yaml: -------------------------------------------------------------------------------- 1 | ## generate base64 encoded string of firebase admin config file and replace here 2 | ## cat file_path | base64 3 | apiVersion: v1 4 | kind: Secret 5 | metadata: 6 | name: firebase-admin-config 7 | data: 8 | firebase-service-account.json: REPLACE_WITH_BASE64_ENCODED_FIREBASE_ADMIN_CONFIG_FILE 9 | -------------------------------------------------------------------------------- /k8/service.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | labels: 6 | app: firebase-middleware-service 7 | name: firebase-middleware-service 8 | spec: 9 | ports: 10 | - port: 8080 11 | protocol: TCP 12 | targetPort: 8080 13 | selector: 14 | app: firebase-middleware 15 | sessionAffinity: None 16 | type: ClusterIP -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.6.0-SNAPSHOT 10 | 11 | 12 | io.thepro 13 | firebase-api-service 14 | 0.0.1-SNAPSHOT 15 | firebase-api-service 16 | Firebase API Service 17 | 18 | 19 | 1.15 20 | 8.0.1 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-security 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | com.google.firebase 34 | firebase-admin 35 | ${firebase.version} 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-devtools 40 | runtime 41 | true 42 | 43 | 44 | org.projectlombok 45 | lombok 46 | true 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | org.junit.vintage 55 | junit-vintage-engine 56 | 57 | 58 | 59 | 60 | org.springframework.security 61 | spring-security-test 62 | test 63 | 64 | 65 | 66 | 67 | 68 | 69 | org.apache.maven.plugins 70 | maven-compiler-plugin 71 | 72 | 1.8 73 | 1.8 74 | 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-maven-plugin 79 | 80 | 81 | 82 | 83 | 84 | spring-milestones 85 | Spring Milestones 86 | https://repo.spring.io/milestone 87 | 88 | false 89 | 90 | 91 | 92 | spring-snapshots 93 | Spring Snapshots 94 | https://repo.spring.io/snapshot 95 | 96 | false 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Firebase Authentication for Spring boot [![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) 2 | 3 | [![Open with ThePro](https://thepro.io/button.svg)](https://thepro.io/post/firebase-authentication-for-spring-boot-rest-api-5V) 4 | 5 | Firebase is a backendless platform to run applications without dedicated backend. But, sometimes you may need to communicate with API of an exisiting backend or you may want a dedicated backend to perform operations that cannot be done through firebase infrastructure. 6 | 7 | This **Spring Boot Starter** is perfect for such situations when you want to extend firebase's authentication menchanism with **Spring Security** to seamlessly create and use protected rest API's. 8 | 9 | ### Configuration 10 | 11 | - Be sure to add the following environment variable globally or project specific run configuration environment variable `GOOGLE_APPLICATION_CREDENTIALS=path_to_firebase_server_config.json` 12 | 13 | - The starter can be configured to use firebase session as client side / strictly server side or both together. 14 | - Htty Only / Secure enabled Session cookies may not work as expected in development hosts (localhost, 120.0.0.1). Adding self signed ssl certificate with reverse proxied host will work perfectly fine. Read this article => [Local Domain Names with SSL for development applications ](https://thepro.io/post/local-domain-names-with-ssl-for-local-development-applications-LG) 15 | - Following application properties can edited to customize for your needs. Sample @ [application.yaml](src/main/resources/) 16 | 17 | ### Role Management 18 | 19 | - Roles can be added through `SecurityRoleService` during registeration of user or manually managed by Super admins 20 | - Super Admins are defined through application property `security.super-admins` 21 | - With roles feature tightly integrated with spring security, Spring authorization annotations like **`@Secured, @RolesAllowed, @PreAuthorize, @PostAuthorized`** etc will work perfectly fine. 22 | - I personally like to define per role annotations like **`@IsSuper, @IsSeller`** for the sake of simplicity. 23 | 24 | ``` 25 | @GetMapping("data") 26 | @isSeller 27 | public String getProtectedData() { 28 | return "You have accessed seller only data from spring boot"; 29 | } 30 | ``` 31 | 32 | - UI useAuth hook also has utility properties like **_ `roles, hasRole, isSuper, isSeller `_** properties exposed accross the application to allow or restrict access to specific UI components. Read this post at thepro.io for more detailed explanation on role management [Firebase and Spring Boot Based Role Management and Authorization](https://thepro.io/post/firebase-and-spring-boot-based-role-management-and-authorization-3D) 33 | 34 | ### End to End Test 35 | 36 | The method I used to solve the problem of testing firebase social authentication is opinionated and may not be suitable to everyone. Simply put, we create a toggleable Test User functionaly that authenticates specific set of static test users through firebase custom token. This solves a lot of issues associated with testing a third party backed authentication flow. Read this post at thepro.io for more in detail explanation [End to End Test Firebase Authentication with Cypress, Spring Boot & Nextjs](https://thepro.io/post/end-to-end-test-firebase-authentication-with-cypress-spring-boot-nextjs-Mg) 37 | 38 | ## Related Tutorials : 39 | 40 | - [Firebase Authentication for Spring Boot Rest API](https://thepro.io/post/firebase-authentication-for-spring-boot-rest-api-5V) 41 | - [Firebase and Spring Boot Based Role Management and Authorization](https://thepro.io/post/firebase-and-spring-boot-based-role-management-and-authorization-3D) 42 | - [Firebase with Spring Boot for Kubernetes Deployment Configuration](https://thepro.io/post/firebase-with-spring-boot-kubernetes-deployment-configuration-RA) 43 | - [Local Domain Names with SSL for development applications ](https://thepro.io/post/local-domain-names-with-ssl-for-local-development-applications-LG) 44 | - [Firebase Server Side Session Authentication with Next.js and Spring Boot](https://thepro.io/post/firebase-server-side-session-authentication-with-next.js-and-spring-boot-py) 45 | - [End to End Test Firebase Authentication with Cypress, Spring Boot & Nextjs](https://thepro.io/post/end-to-end-test-firebase-authentication-with-cypress-spring-boot-nextjs-Mg) 46 | 47 | ### UI Demo 48 | 49 | - Nextjs application demonstrating Client side firebase session. [ui-client-side-session-demo](ui-client-side-session-demo/) 50 | - Nextjs application demonstrating Server side firebase session. [ui-server-side-session-demo](ui-server-side-session-demo/) 51 | 52 | ### Screenshots 53 | 54 | #### Client Side Session Screenshots 55 | 56 | | Logged out | Logged In | 57 | | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | 58 | | ![Image of UI Loggedout](https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/master/ui-client-side-session-demo/screenshots/loggedout.png) | ![Image of UI LoggedIn ](https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/master/ui-client-side-session-demo/screenshots/loggedin.png) | 59 | | | ![Image of UI Loggedin Seller](https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/master/ui-client-side-session-demo/screenshots/loggedin_seller.png) | 60 | 61 | #### Server Side Session Screenshots 62 | 63 | ![Image of UI Server Side Session](https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/master/ui-server-side-session-demo/screenshots/screenshot.png) 64 | 65 | #### Cypress End to End Tests Screencapture 66 | 67 | ![Image of End to End Tests ](https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/master/ui-server-side-session-demo/screenshots/cypress_auth_test.gif) 68 | 69 | ## Author 70 | 71 | 👤 **Gladius** 72 | 73 | - Website: thepro.io/@/gladius 74 | - Github: [@gladius](https://github.com/gladius) 75 | 76 | ## Show your support 77 | 78 | Give a ⭐️ if this project helped you! 79 | 80 | ## License 81 | 82 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 83 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/APIServiceApplication.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | 7 | 8 | @SpringBootApplication 9 | public class APIServiceApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(APIServiceApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/config/FirebaseConfig.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.config; 2 | 3 | import java.io.IOException; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Primary; 9 | 10 | import com.google.auth.oauth2.GoogleCredentials; 11 | import com.google.cloud.firestore.Firestore; 12 | import com.google.cloud.firestore.FirestoreOptions; 13 | import com.google.firebase.FirebaseApp; 14 | import com.google.firebase.FirebaseOptions; 15 | import com.google.firebase.auth.FirebaseAuth; 16 | import com.google.firebase.database.FirebaseDatabase; 17 | import com.google.firebase.messaging.FirebaseMessaging; 18 | import com.google.firebase.remoteconfig.FirebaseRemoteConfig; 19 | 20 | import io.thepro.apiservice.security.models.SecurityProperties; 21 | 22 | @Configuration 23 | public class FirebaseConfig { 24 | 25 | @Autowired 26 | private SecurityProperties secProps; 27 | 28 | @Primary 29 | @Bean 30 | public FirebaseApp getfirebaseApp() throws IOException { 31 | FirebaseOptions options = FirebaseOptions.builder().setCredentials(GoogleCredentials.getApplicationDefault()) 32 | .setDatabaseUrl(secProps.getFirebaseProps().getDatabaseUrl()).build(); 33 | if (FirebaseApp.getApps().isEmpty()) { 34 | FirebaseApp.initializeApp(options); 35 | } 36 | return FirebaseApp.getInstance(); 37 | } 38 | 39 | @Bean 40 | public FirebaseAuth getAuth() throws IOException { 41 | return FirebaseAuth.getInstance(getfirebaseApp()); 42 | } 43 | 44 | @Bean 45 | public FirebaseDatabase firebaseDatabase() throws IOException { 46 | return FirebaseDatabase.getInstance(); 47 | } 48 | 49 | @Bean 50 | public Firestore getDatabase() throws IOException { 51 | FirestoreOptions firestoreOptions = FirestoreOptions.newBuilder() 52 | .setCredentials(GoogleCredentials.getApplicationDefault()).build(); 53 | return firestoreOptions.getService(); 54 | } 55 | 56 | @Bean 57 | public FirebaseMessaging getMessaging() throws IOException { 58 | return FirebaseMessaging.getInstance(getfirebaseApp()); 59 | } 60 | 61 | @Bean 62 | public FirebaseRemoteConfig getRemoteConfig() throws IOException { 63 | return FirebaseRemoteConfig.getInstance(getfirebaseApp()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/config/JacksonConfig.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.Primary; 6 | import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; 7 | 8 | import com.fasterxml.jackson.databind.ObjectMapper; 9 | 10 | @Configuration 11 | public class JacksonConfig { 12 | @Primary 13 | @Bean 14 | public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { 15 | ObjectMapper objectMapper = builder.build(); 16 | return objectMapper; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/controllers/ProtectedController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.controllers; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import io.thepro.apiservice.security.SecurityService; 9 | 10 | @RestController 11 | @RequestMapping("protected") 12 | public class ProtectedController { 13 | 14 | @Autowired 15 | private SecurityService securityService; 16 | 17 | @GetMapping("data") 18 | public String getProtectedData() { 19 | String name = securityService.getUser().getName(); 20 | return name.split("\\s+")[0] + ", you have accessed protected data from spring boot"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/controllers/PublicController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.controllers; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("public") 9 | public class PublicController { 10 | 11 | @GetMapping("data") 12 | public String getPublicData() { 13 | 14 | return "You have accessed public data from spring boot"; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/controllers/SellerController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.controllers; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import io.thepro.apiservice.security.roles.IsSeller; 8 | 9 | @RestController 10 | @RequestMapping("seller") 11 | public class SellerController { 12 | 13 | @GetMapping("data") 14 | @IsSeller 15 | public String getProtectedData() { 16 | return "You have accessed seller only data from spring boot"; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/controllers/SuperAdminController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.controllers; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import com.google.firebase.auth.FirebaseAuth; 10 | import com.google.firebase.auth.UserRecord; 11 | 12 | import io.thepro.apiservice.security.SecurityService; 13 | import io.thepro.apiservice.security.roles.IsSuper; 14 | import io.thepro.apiservice.security.roles.RoleService; 15 | 16 | @RestController 17 | @RequestMapping("super") 18 | public class SuperAdminController { 19 | 20 | @Autowired 21 | RoleService securityRoleService; 22 | 23 | @Autowired 24 | private SecurityService securityService; 25 | 26 | @Autowired 27 | FirebaseAuth firebaseAuth; 28 | 29 | @GetMapping("user") 30 | @IsSuper 31 | public UserRecord getUser(@RequestParam String email) throws Exception { 32 | return firebaseAuth.getUserByEmail(email); 33 | } 34 | 35 | @GetMapping("data") 36 | @IsSuper 37 | public String getSuperData() { 38 | String name = securityService.getUser().getName(); 39 | return name.split("\\s+")[0] + ", you have accessed super data from spring boot"; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/CookieService.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import javax.servlet.http.Cookie; 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.web.util.WebUtils; 11 | 12 | import io.thepro.apiservice.security.models.SecurityProperties; 13 | 14 | @Service 15 | public class CookieService { 16 | 17 | @Autowired 18 | HttpServletRequest httpServletRequest; 19 | 20 | @Autowired 21 | HttpServletResponse httpServletResponse; 22 | 23 | @Autowired 24 | SecurityProperties restSecProps; 25 | 26 | public Cookie getCookie(String name) { 27 | return WebUtils.getCookie(httpServletRequest, name); 28 | } 29 | 30 | public void setCookie(String name, String value, int expiryInDays) { 31 | int expiresInSeconds = (int) TimeUnit.DAYS.toSeconds(expiryInDays); 32 | Cookie cookie = new Cookie(name, value); 33 | cookie.setSecure(restSecProps.getCookieProps().isSecure()); 34 | cookie.setPath(restSecProps.getCookieProps().getPath()); 35 | cookie.setDomain(restSecProps.getCookieProps().getDomain()); 36 | cookie.setMaxAge(expiresInSeconds); 37 | httpServletResponse.addCookie(cookie); 38 | } 39 | 40 | public void setSecureCookie(String name, String value, int expiryInDays) { 41 | int expiresInSeconds = (int) TimeUnit.DAYS.toSeconds(expiryInDays); 42 | Cookie cookie = new Cookie(name, value); 43 | cookie.setHttpOnly(restSecProps.getCookieProps().isHttpOnly()); 44 | cookie.setSecure(restSecProps.getCookieProps().isSecure()); 45 | cookie.setPath(restSecProps.getCookieProps().getPath()); 46 | cookie.setDomain(restSecProps.getCookieProps().getDomain()); 47 | cookie.setMaxAge(expiresInSeconds); 48 | httpServletResponse.addCookie(cookie); 49 | } 50 | 51 | public void setSecureCookie(String name, String value) { 52 | int expiresInMinutes = restSecProps.getCookieProps().getMaxAgeInMinutes(); 53 | setSecureCookie(name, value, expiresInMinutes); 54 | } 55 | 56 | public void deleteSecureCookie(String name) { 57 | int expiresInSeconds = 0; 58 | Cookie cookie = new Cookie(name, null); 59 | cookie.setHttpOnly(restSecProps.getCookieProps().isHttpOnly()); 60 | cookie.setSecure(restSecProps.getCookieProps().isSecure()); 61 | cookie.setPath(restSecProps.getCookieProps().getPath()); 62 | cookie.setDomain(restSecProps.getCookieProps().getDomain()); 63 | cookie.setMaxAge(expiresInSeconds); 64 | httpServletResponse.addCookie(cookie); 65 | } 66 | 67 | public void deleteCookie(String name) { 68 | int expiresInSeconds = 0; 69 | Cookie cookie = new Cookie(name, null); 70 | cookie.setPath(restSecProps.getCookieProps().getPath()); 71 | cookie.setDomain(restSecProps.getCookieProps().getDomain()); 72 | cookie.setMaxAge(expiresInSeconds); 73 | httpServletResponse.addCookie(cookie); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security; 2 | 3 | import java.io.IOException; 4 | import java.sql.Timestamp; 5 | import java.util.Date; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.context.annotation.Bean; 15 | import org.springframework.context.annotation.Configuration; 16 | import org.springframework.http.HttpMethod; 17 | import org.springframework.http.HttpStatus; 18 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 20 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 21 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 22 | import org.springframework.security.config.http.SessionCreationPolicy; 23 | import org.springframework.security.core.AuthenticationException; 24 | import org.springframework.security.web.AuthenticationEntryPoint; 25 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 26 | import org.springframework.web.cors.CorsConfiguration; 27 | import org.springframework.web.cors.CorsConfigurationSource; 28 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 29 | 30 | import com.fasterxml.jackson.databind.ObjectMapper; 31 | 32 | import io.thepro.apiservice.security.models.SecurityProperties; 33 | 34 | @Configuration 35 | @EnableWebSecurity 36 | @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) 37 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 38 | 39 | @Autowired 40 | private ObjectMapper objectMapper; 41 | 42 | @Autowired 43 | private SecurityProperties restSecProps; 44 | 45 | @Autowired 46 | private SecurityFilter tokenAuthenticationFilter; 47 | 48 | @Bean 49 | public AuthenticationEntryPoint restAuthenticationEntryPoint() { 50 | return new AuthenticationEntryPoint() { 51 | @Override 52 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 53 | AuthenticationException e) throws IOException, ServletException { 54 | Map errorObject = new HashMap(); 55 | int errorCode = 401; 56 | errorObject.put("message", "Unauthorized access of protected resource, invalid credentials"); 57 | errorObject.put("error", HttpStatus.UNAUTHORIZED); 58 | errorObject.put("code", errorCode); 59 | errorObject.put("timestamp", new Timestamp(new Date().getTime())); 60 | httpServletResponse.setContentType("application/json;charset=UTF-8"); 61 | httpServletResponse.setStatus(errorCode); 62 | httpServletResponse.getWriter().write(objectMapper.writeValueAsString(errorObject)); 63 | } 64 | }; 65 | } 66 | 67 | @Bean 68 | CorsConfigurationSource corsConfigurationSource() { 69 | CorsConfiguration configuration = new CorsConfiguration(); 70 | configuration.setAllowedOrigins(restSecProps.getAllowedOrigins()); 71 | configuration.setAllowedMethods(restSecProps.getAllowedMethods()); 72 | configuration.setAllowedHeaders(restSecProps.getAllowedHeaders()); 73 | configuration.setAllowCredentials(restSecProps.isAllowCredentials()); 74 | configuration.setExposedHeaders(restSecProps.getExposedHeaders()); 75 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 76 | source.registerCorsConfiguration("/**", configuration); 77 | return source; 78 | } 79 | 80 | @Override 81 | protected void configure(HttpSecurity http) throws Exception { 82 | http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().formLogin().disable() 83 | .httpBasic().disable().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint()) 84 | .and().authorizeRequests() 85 | .antMatchers(restSecProps.getAllowedPublicApis().stream().toArray(String[]::new)).permitAll() 86 | .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated().and() 87 | .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) 88 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/SecurityFilter.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.Cookie; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 15 | import org.springframework.security.core.GrantedAuthority; 16 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 17 | import org.springframework.security.core.context.SecurityContextHolder; 18 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 19 | import org.springframework.stereotype.Component; 20 | import org.springframework.web.filter.OncePerRequestFilter; 21 | 22 | import com.google.firebase.auth.FirebaseAuth; 23 | import com.google.firebase.auth.FirebaseAuthException; 24 | import com.google.firebase.auth.FirebaseToken; 25 | 26 | import io.thepro.apiservice.security.models.Credentials; 27 | import io.thepro.apiservice.security.models.Credentials.CredentialType; 28 | import io.thepro.apiservice.security.models.SecurityProperties; 29 | import io.thepro.apiservice.security.models.User; 30 | import io.thepro.apiservice.security.roles.RoleConstants; 31 | import io.thepro.apiservice.security.roles.RoleService; 32 | import lombok.extern.slf4j.Slf4j; 33 | 34 | @Component 35 | @Slf4j 36 | public class SecurityFilter extends OncePerRequestFilter { 37 | 38 | @Autowired 39 | private SecurityService securityService; 40 | 41 | @Autowired 42 | private CookieService cookieUtils; 43 | 44 | @Autowired 45 | private SecurityProperties securityProps; 46 | 47 | @Autowired 48 | RoleService securityRoleService; 49 | 50 | @Autowired 51 | private FirebaseAuth firebaseAuth; 52 | 53 | @Override 54 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 55 | throws ServletException, IOException { 56 | authorize(request); 57 | filterChain.doFilter(request, response); 58 | } 59 | 60 | private void authorize(HttpServletRequest request) { 61 | String sessionCookieValue = null; 62 | FirebaseToken decodedToken = null; 63 | CredentialType type = null; 64 | // Token verification 65 | boolean strictServerSessionEnabled = securityProps.getFirebaseProps().isEnableStrictServerSession(); 66 | Cookie sessionCookie = cookieUtils.getCookie("session"); 67 | String token = securityService.getBearerToken(request); 68 | try { 69 | if (sessionCookie != null) { 70 | sessionCookieValue = sessionCookie.getValue(); 71 | decodedToken = firebaseAuth.verifySessionCookie(sessionCookieValue, 72 | securityProps.getFirebaseProps().isEnableCheckSessionRevoked()); 73 | type = CredentialType.SESSION; 74 | } else if (!strictServerSessionEnabled && token != null && !token.equals("null") 75 | && !token.equalsIgnoreCase("undefined")) { 76 | decodedToken = firebaseAuth.verifyIdToken(token); 77 | type = CredentialType.ID_TOKEN; 78 | } 79 | } catch (FirebaseAuthException e) { 80 | log.error("Firebase Exception:: ", e.getLocalizedMessage()); 81 | } 82 | List authorities = new ArrayList<>(); 83 | User user = firebaseTokenToUserDto(decodedToken); 84 | // Handle roles 85 | if (user != null) { 86 | // Handle Super Role 87 | if (securityProps.getSuperAdmins().contains(user.getEmail())) { 88 | if (!decodedToken.getClaims().containsKey(RoleConstants.ROLE_SUPER)) { 89 | try { 90 | securityRoleService.addRole(decodedToken.getUid(), RoleConstants.ROLE_SUPER); 91 | } catch (Exception e) { 92 | log.error("Super Role registeration expcetion ", e); 93 | } 94 | } 95 | authorities.add(new SimpleGrantedAuthority(RoleConstants.ROLE_SUPER)); 96 | } 97 | // Handle Other roles 98 | decodedToken.getClaims().forEach((k, v) -> authorities.add(new SimpleGrantedAuthority(k))); 99 | // Set security context 100 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, 101 | new Credentials(type, decodedToken, token, sessionCookieValue), authorities); 102 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 103 | SecurityContextHolder.getContext().setAuthentication(authentication); 104 | } 105 | } 106 | 107 | private User firebaseTokenToUserDto(FirebaseToken decodedToken) { 108 | User user = null; 109 | if (decodedToken != null) { 110 | user = new User(); 111 | user.setUid(decodedToken.getUid()); 112 | user.setName(decodedToken.getName()); 113 | user.setEmail(decodedToken.getEmail()); 114 | user.setPicture(decodedToken.getPicture()); 115 | user.setIssuer(decodedToken.getIssuer()); 116 | user.setEmailVerified(decodedToken.isEmailVerified()); 117 | } 118 | return user; 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/SecurityService.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import org.springframework.security.core.context.SecurityContext; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.util.StringUtils; 9 | 10 | import io.thepro.apiservice.security.models.Credentials; 11 | import io.thepro.apiservice.security.models.User; 12 | 13 | @Service 14 | public class SecurityService { 15 | 16 | public User getUser() { 17 | User userPrincipal = null; 18 | SecurityContext securityContext = SecurityContextHolder.getContext(); 19 | Object principal = securityContext.getAuthentication().getPrincipal(); 20 | if (principal instanceof User) { 21 | userPrincipal = ((User) principal); 22 | } 23 | return userPrincipal; 24 | } 25 | 26 | public Credentials getCredentials() { 27 | SecurityContext securityContext = SecurityContextHolder.getContext(); 28 | return (Credentials) securityContext.getAuthentication().getCredentials(); 29 | } 30 | 31 | public String getBearerToken(HttpServletRequest request) { 32 | String bearerToken = null; 33 | String authorization = request.getHeader("Authorization"); 34 | if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) { 35 | bearerToken = authorization.substring(7, authorization.length()); 36 | } 37 | return bearerToken; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/SessionController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import com.google.firebase.auth.FirebaseAuth; 14 | import com.google.firebase.auth.FirebaseAuthException; 15 | import com.google.firebase.auth.SessionCookieOptions; 16 | 17 | import io.thepro.apiservice.security.models.Credentials.CredentialType; 18 | import io.thepro.apiservice.security.models.SecurityProperties; 19 | import io.thepro.apiservice.security.models.User; 20 | 21 | @RestController 22 | @RequestMapping("session") 23 | public class SessionController { 24 | 25 | @Autowired 26 | private SecurityService securityService; 27 | 28 | @Autowired 29 | private CookieService cookieUtils; 30 | 31 | @Autowired 32 | private SecurityProperties secProps; 33 | 34 | @PostMapping("login") 35 | public void sessionLogin(HttpServletRequest request) { 36 | String idToken = securityService.getBearerToken(request); 37 | User user = securityService.getUser(); 38 | int sessionExpiryDays = secProps.getFirebaseProps().getSessionExpiryInDays(); 39 | long expiresIn = TimeUnit.DAYS.toMillis(sessionExpiryDays); 40 | SessionCookieOptions options = SessionCookieOptions.builder().setExpiresIn(expiresIn).build(); 41 | try { 42 | String sessionCookieValue = FirebaseAuth.getInstance().createSessionCookie(idToken, options); 43 | cookieUtils.setSecureCookie("session", sessionCookieValue, sessionExpiryDays); 44 | cookieUtils.setCookie("authenticated", Boolean.toString(true), sessionExpiryDays); 45 | cookieUtils.setCookie("fullname", user.getName().replaceAll("\\s+", "_").toLowerCase(), sessionExpiryDays); 46 | cookieUtils.setCookie("pic", user.getPicture(), sessionExpiryDays); 47 | } catch (FirebaseAuthException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | @PostMapping("logout") 53 | public void sessionLogout() { 54 | if (securityService.getCredentials().getType() == CredentialType.SESSION 55 | && secProps.getFirebaseProps().isEnableLogoutEverywhere()) { 56 | try { 57 | FirebaseAuth.getInstance().revokeRefreshTokens(securityService.getUser().getUid()); 58 | } catch (FirebaseAuthException e) { 59 | e.printStackTrace(); 60 | } 61 | } 62 | cookieUtils.deleteSecureCookie("session"); 63 | cookieUtils.deleteCookie("authenticated"); 64 | cookieUtils.deleteCookie("fullname"); 65 | cookieUtils.deleteCookie("pic"); 66 | } 67 | 68 | @PostMapping("me") 69 | public User getUser() { 70 | return securityService.getUser(); 71 | } 72 | 73 | @GetMapping("create/token") 74 | public String getCustomToken() throws FirebaseAuthException { 75 | return FirebaseAuth.getInstance().createCustomToken(String.valueOf(securityService.getUser().getUid())); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/models/CookieProperties.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.models; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class CookieProperties { 7 | private String domain; 8 | private String path; 9 | private boolean httpOnly; 10 | private boolean secure; 11 | private int maxAgeInMinutes; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/models/Credentials.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.models; 2 | 3 | import com.google.firebase.auth.FirebaseToken; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class Credentials { 11 | 12 | public enum CredentialType { 13 | ID_TOKEN, SESSION 14 | } 15 | 16 | private CredentialType type; 17 | private FirebaseToken decodedToken; 18 | private String idToken; 19 | private String session; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/models/FirebaseProperties.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.models; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class FirebaseProperties { 7 | 8 | private int sessionExpiryInDays; 9 | private String databaseUrl; 10 | private boolean enableStrictServerSession; 11 | private boolean enableCheckSessionRevoked; 12 | private boolean enableLogoutEverywhere; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/models/SecurityProperties.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.models; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.stereotype.Component; 7 | 8 | import lombok.Data; 9 | 10 | @Component 11 | @ConfigurationProperties(prefix = "security") 12 | @Data 13 | public class SecurityProperties { 14 | 15 | private CookieProperties cookieProps; 16 | private FirebaseProperties firebaseProps; 17 | private boolean allowCredentials; 18 | private List allowedOrigins; 19 | private List allowedHeaders; 20 | private List exposedHeaders; 21 | private List allowedMethods; 22 | private List allowedPublicApis; 23 | List superAdmins; 24 | List validApplicationRoles; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/models/User.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.models; 2 | 3 | import java.io.Serializable; 4 | 5 | import lombok.Data; 6 | 7 | @Data 8 | public class User implements Serializable { 9 | 10 | private static final long serialVersionUID = 4408418647685225829L; 11 | private String uid; 12 | private String name; 13 | private String email; 14 | private boolean isEmailVerified; 15 | private String issuer; 16 | private String picture; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/IsSeller.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | 10 | @Target(ElementType.METHOD) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @PreAuthorize("hasRole('SELLER')") 13 | public @interface IsSeller { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/IsSuper.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | 10 | @Target(ElementType.METHOD) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @PreAuthorize("hasRole('SUPER')") 13 | public @interface IsSuper { 14 | } -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/RoleConstants.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | public class RoleConstants { 4 | public static final String ROLE_SUPER = "ROLE_SUPER"; 5 | 6 | public static final String ROLE_ADMIN = "ROLE_ADMIN"; 7 | 8 | public static final String ROLE_SELLER = "ROLE_SELLER"; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/RoleController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.DeleteMapping; 5 | import org.springframework.web.bind.annotation.PutMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestParam; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import com.google.firebase.auth.FirebaseAuth; 11 | 12 | @RestController 13 | @RequestMapping("role") 14 | public class RoleController { 15 | 16 | @Autowired 17 | RoleService roleService; 18 | 19 | 20 | @Autowired 21 | FirebaseAuth firebaseAuth; 22 | 23 | 24 | @PutMapping("add") 25 | @IsSuper 26 | public void addRole(@RequestParam String uid, @RequestParam String role) throws Exception { 27 | roleService.addRole(uid, role); 28 | } 29 | 30 | @DeleteMapping("remove") 31 | @IsSuper 32 | public void removeRole(@RequestParam String uid, @RequestParam String role) { 33 | roleService.removeRole(uid, role); 34 | 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/RoleService.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | public interface RoleService { 4 | 5 | void addRole(String uid, String role) throws Exception; 6 | 7 | void removeRole(String uid, String role); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/roles/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.roles; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.google.firebase.auth.FirebaseAuth; 10 | import com.google.firebase.auth.FirebaseAuthException; 11 | import com.google.firebase.auth.UserRecord; 12 | 13 | import io.thepro.apiservice.security.models.SecurityProperties; 14 | import lombok.extern.slf4j.Slf4j; 15 | 16 | @Service 17 | @Slf4j 18 | public class RoleServiceImpl implements RoleService { 19 | 20 | @Autowired 21 | FirebaseAuth firebaseAuth; 22 | 23 | @Autowired 24 | private SecurityProperties securityProps; 25 | 26 | @Override 27 | public void addRole(String uid, String role) throws Exception { 28 | try { 29 | UserRecord user = firebaseAuth.getUser(uid); 30 | Map claims = new HashMap<>(); 31 | user.getCustomClaims().forEach((k, v) -> claims.put(k, v)); 32 | if (securityProps.getValidApplicationRoles().contains(role)) { 33 | if (!claims.containsKey(role)) { 34 | claims.put(role, true); 35 | } 36 | firebaseAuth.setCustomUserClaims(uid, claims); 37 | } else { 38 | throw new Exception("Not a valid Application role, Allowed roles => " 39 | + securityProps.getValidApplicationRoles().toString()); 40 | } 41 | 42 | } catch (FirebaseAuthException e) { 43 | log.error("Firebase Auth Error ", e); 44 | } 45 | 46 | } 47 | 48 | @Override 49 | public void removeRole(String uid, String role) { 50 | try { 51 | UserRecord user = firebaseAuth.getUser(uid); 52 | Map claims = new HashMap<>(); 53 | user.getCustomClaims().forEach((k, v) -> claims.put(k, v)); 54 | if (claims.containsKey(role)) { 55 | claims.remove(role); 56 | } 57 | firebaseAuth.setCustomUserClaims(uid, claims); 58 | } catch (FirebaseAuthException e) { 59 | log.error("Firebase Auth Error ", e); 60 | } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/test/TestAuthController.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.test; 2 | import org.springframework.beans.factory.annotation.Autowired; 3 | import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @ConditionalOnExpression("${test.login.enabled:false}") 11 | @RequestMapping("test") 12 | public class TestAuthController { 13 | 14 | @Autowired 15 | TestAuthService testAuthService; 16 | 17 | @PostMapping("/login/{email}") 18 | public String testLogin(@PathVariable("email") String email) throws Exception { 19 | System.out.println("test login uid :: " + email); 20 | return testAuthService.authorizeTestLogin(email); 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/test/TestAuthService.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.test; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import javax.annotation.PostConstruct; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; 12 | import org.springframework.core.io.Resource; 13 | import org.springframework.stereotype.Service; 14 | 15 | import com.fasterxml.jackson.core.type.TypeReference; 16 | import com.fasterxml.jackson.databind.ObjectMapper; 17 | import com.google.firebase.auth.FirebaseAuth; 18 | 19 | @Service 20 | @ConditionalOnExpression("${test.login.enabled:false}") 21 | public class TestAuthService { 22 | 23 | @Autowired 24 | FirebaseAuth firebaseAuth; 25 | 26 | @Value("classpath:data/test_users.json") 27 | private Resource resourceFile; 28 | 29 | @Autowired 30 | private ObjectMapper jsonMapper; 31 | 32 | private HashMap testUsers; 33 | 34 | @PostConstruct 35 | public void init() throws IOException { 36 | testUsers = jsonMapper.readValue(resourceFile.getInputStream(), new TypeReference>() { 37 | }); 38 | } 39 | 40 | public String authorizeTestLogin(String email) throws Exception { 41 | if (testUsers.containsKey(email)) { 42 | TestUser testUser = testUsers.get(email); 43 | Map developerClaims = new HashMap(); 44 | developerClaims.put("name", testUser.getName()); 45 | developerClaims.put("email", testUser.getEmail()); 46 | developerClaims.put("ROLE_SUPER", testUser.isSuper()); 47 | return firebaseAuth.createCustomToken(testUser.getUid().toString(), developerClaims); 48 | } else { 49 | throw new Exception("Invalid User"); 50 | } 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/main/java/io/thepro/apiservice/security/test/TestUser.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice.security.test; 2 | import lombok.Data; 3 | 4 | @Data 5 | public class TestUser { 6 | 7 | private Long uid; 8 | private String name; 9 | private String email; 10 | private boolean isSuper; 11 | 12 | } -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | 2 | server: 3 | port: 8090 4 | security: 5 | firebase-props: 6 | database-url: ${FIREBASE_DATABASE} 7 | enable-strict-server-session: ${ENABLE_STRICT_SERVER_SESSION} 8 | enable-check-session-revoked: false 9 | enable-logout-everywhere: false 10 | session-expiry-in-days: 5 11 | cookie-props: 12 | max-age-in-minutes: 7200 13 | http-only: true 14 | secure: true 15 | domain: ${CORS_DOMAIN} 16 | path: / 17 | allow-credentials: true 18 | allowed-origins: 19 | - https://${CORS_DOMAIN} 20 | - http://localhost:3000 21 | allowed-methods: 22 | - GET 23 | - POST 24 | - PUT 25 | - PATCH 26 | - DELETE 27 | - OPTIONS 28 | allowed-headers: 29 | - Authorization 30 | - Origin 31 | - Content-Type 32 | - Accept 33 | - Accept-Encoding 34 | - Accept-Language 35 | - Access-Control-Allow-Origin 36 | - Access-Control-Allow-Headers 37 | - Access-Control-Request-Method 38 | - X-Requested-With 39 | - X-Auth-Token 40 | - X-Xsrf-Token 41 | - Cache-Control 42 | - Id-Token 43 | allowed-public-apis: 44 | - /favicon.ico 45 | - /session/login 46 | - /public/* 47 | - /test/** 48 | exposed-headers: 49 | - X-Xsrf-Token 50 | valid-application-roles: 51 | - ROLE_SUPER 52 | - ROLE_ADMIN 53 | - ROLE_SELLER 54 | - ROLE_CUSTOMER 55 | super-admins: ${SUPER_ADMINS} 56 | test: 57 | login: 58 | enabled: ${TEST_LOGIN_ENABLED} 59 | logging: 60 | level: 61 | root: WARN 62 | org: 63 | springframework: 64 | web: DEBUG 65 | hibernate: ERROR 66 | io: 67 | thepro: DEBUG 68 | pattern: 69 | console: "%d{HH:mm:ss} || %highlight(%5p) < %highlight(%-35.35logger{35}) > %highlight(%m%n)" 70 | -------------------------------------------------------------------------------- /src/main/resources/data/test_users.json: -------------------------------------------------------------------------------- 1 | { 2 | "johnwick@online.com": { 3 | "uid": 3, 4 | "name": "John Wick", 5 | "isSuper": false, 6 | "email": "johnwick@online.com" 7 | }, 8 | "jakeperalta@online.com": { 9 | "uid": 4, 10 | "name": "jake peralta", 11 | "isSuper": false, 12 | "email": "jakeperalta@online.com" 13 | }, 14 | "superman@online.com": { 15 | "uid": 5, 16 | "name": "super man", 17 | "isSuper": true, 18 | "email": "superman@online.com" 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/resources/readme.md: -------------------------------------------------------------------------------- 1 | ## Sample @ [application.properties](src/main/resources/application.yaml) 2 | 3 | | Properties | Description | DataType | 4 | | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | 5 | | `security.firebase-props.database-url` | Firebase Database URL found in Firebase Web SDK config | String | 6 | | `security.firebase-props.enable-strict-server-session` | server will only look for session cookie to verify request | Boolean | 7 | | `security.firebase-props.enable-check-session-revoked` | will check if firebase session was revoked elsewhere, this will also add overhead of few seconds to each request. Applicable only if `enable-strict-server-session` enabled | Boolean | 8 | | `security.firebase-props.enable-logout-everywhere` | firebase will revoke refresh tokens everywhere. Applicable only if `enable-strict-server-session` enabled | Boolean | 9 | | `security.firebase-props.session-expiry-in-days` | Expiration time for long lived session. Applicable only if `enable-strict-server-session` enabled | Integer | 10 | | `security.cookie-props.max-age-in-minutes` | Default Cookie expiration time. | Integer | 11 | | `security.cookie-props.http-only` | Cookies will not be accessible to client side scripts. | Boolean | 12 | | `security.cookie-props.secure` | Cookies will be sent only over secure https channel | Boolean | 13 | | `security.cookie-props.domain` | Cookies will only be available on provided domain eg:- "demo.dev" | String | 14 | | `security.cookie-props.path` | Cookies will only available on provided path. Path "/" will allow access from any page. | String | 15 | | `security.allow-credentials` | Lets client know that server accepts cookies and other credentials from `security.allowed-origins`. | String | 16 | | `security.allowed-origins` | An array of allowed cross origin domain names eg:- https://demo.dev. | Array | 17 | | `security.allowed-methods` | An array of HTTP methods server will accept | Array | 18 | | `security.allowed-headers` | An array of HTTP headers server will accept | Array | 19 | | `security.allowed-public-apis` | An array of rest path on server which can be publicaly accessible. path can be wildcard ie. `/public/*` will accept `/public/path1,/public/path2` | Array | 20 | | `security.exposed-headers` | An array of exposed headers, this is required only if CSRF tokens are generated by the server | Array | 21 | | `valid-application-roles:` | Valid application roles, Add or remove roles. Roles must be of format ROLE\_`ROLENAME` | Array | 22 | | `security.super-admins:` | An array of user email id's to be designated as super admins | Array | 23 | -------------------------------------------------------------------------------- /src/test/java/io/thepro/apiservice/ApiServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package io.thepro.apiservice; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ApiServiceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env 29 | .env.local 30 | .env.development.local 31 | .env.test.local 32 | .env.production.local 33 | 34 | # vercel 35 | .vercel 36 | 37 | yarn.lock -------------------------------------------------------------------------------- /ui-client-side-session-demo/README.md: -------------------------------------------------------------------------------- 1 | # Nextjs Demo using Client side Firebase session 2 | 3 | ## Installation 4 | 5 | Add .env file in the project root folder with values from firebase config json and spring boot host and port 6 | 7 | ``` 8 | NEXT_PUBLIC_API_KEY=REPLACE_WITH_API_KEY 9 | NEXT_PUBLIC_AUTH_DOMAIN=REPLACE_WITH_AUTH_DOMAIN 10 | NEXT_PUBLIC_DB_URL=REPLACE_WITH_DB_URL 11 | NEXT_PUBLIC_PROJECT_ID=REPLACE_WITH_PROJECT_ID 12 | NEXT_PUBLIC_APP_ID=REPLACE_WITH_APP_ID 13 | NEXT_PUBLIC_MIDDLEWARE_URL=REPLACE_WITH_SPRING_BOOT_URL 14 | ``` 15 | 16 | First, run the development server: 17 | 18 | ```bash 19 | npm run dev 20 | # or 21 | yarn dev 22 | ``` 23 | 24 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 25 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./src" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "firebase", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev -p 4000", 7 | "build": "next build", 8 | "start": "next start" 9 | }, 10 | "dependencies": { 11 | "axios": "^0.21.4", 12 | "firebase": "^9.0.2", 13 | "next": "^11.1.2", 14 | "react": "^17.0.2", 15 | "react-dom": "^17.0.2" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-client-side-session-demo/public/favicon.ico -------------------------------------------------------------------------------- /ui-client-side-session-demo/screenshots/loggedin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-client-side-session-demo/screenshots/loggedin.png -------------------------------------------------------------------------------- /ui-client-side-session-demo/screenshots/loggedin_seller.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-client-side-session-demo/screenshots/loggedin_seller.png -------------------------------------------------------------------------------- /ui-client-side-session-demo/screenshots/loggedout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-client-side-session-demo/screenshots/loggedout.png -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/components/data/demo.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import axios from "axios"; 3 | import { useAuth } from "contexts/useAuth.js"; 4 | 5 | const backend = ({ url, label }) => { 6 | const { idToken } = useAuth(); 7 | const [data, setData] = useState(null); 8 | const [status, setStatus] = useState(null); 9 | 10 | useEffect(() => { 11 | axios({ 12 | url: process.env.NEXT_PUBLIC_MIDDLEWARE_URL + url, 13 | method: "GET", 14 | headers: { 15 | Authorization: "Bearer " + idToken, 16 | }, 17 | }) 18 | .then((res) => { 19 | setData(res.data); 20 | setStatus(res.status); 21 | }) 22 | .catch((error) => { 23 | if (error.response) { 24 | setData(error.response.data.message); 25 | setStatus(error.response.data.code); 26 | } 27 | }); 28 | }, [idToken]); 29 | return ( 30 | <> 31 | {data && ( 32 | <> 33 | 34 |
{data}
35 | 36 | 37 | {url} 38 | 39 | 40 | 44 | {status} 45 | 46 | 47 | 48 | )} 49 | 50 | ); 51 | }; 52 | 53 | export default backend; 54 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/components/navbar.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useAuth } from "contexts/useAuth.js"; 3 | 4 | const Navbar = () => { 5 | const { user, login, logout } = useAuth(); 6 | return ( 7 |
8 |

Spring Boot Firebase Authorization

9 | {user != null ? ( 10 |
11 |
12 | 13 |
{user.name}
14 |
15 |
16 | 23 |
24 |
25 | ) : ( 26 |
27 | 34 |
35 | )} 36 |
37 | ); 38 | }; 39 | 40 | export default Navbar; 41 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/components/rolemanager/rolemanager.js: -------------------------------------------------------------------------------- 1 | import { useState } from "react"; 2 | import { useAuth } from "contexts/useAuth"; 3 | import axios from "axios"; 4 | import RolesView from "components/roles/roles"; 5 | 6 | const RoleManager = () => { 7 | const { loadingUser, user, isSeller, idToken, refreshToken } = useAuth(); 8 | const [loading, setLoading] = useState(false); 9 | 10 | const addRole = (role) => { 11 | setLoading(true); 12 | axios({ 13 | url: 14 | process.env.NEXT_PUBLIC_MIDDLEWARE_URL + 15 | "/role/add?uid=" + 16 | user.user_id + 17 | "&role=" + 18 | role, 19 | method: "PUT", 20 | headers: { 21 | Authorization: "Bearer " + idToken, 22 | }, 23 | }) 24 | .then(() => refreshToken()) 25 | .then(() => setLoading(false)); 26 | }; 27 | 28 | const removeRole = (role) => { 29 | setLoading(true); 30 | axios({ 31 | url: 32 | process.env.NEXT_PUBLIC_MIDDLEWARE_URL + 33 | "/role/remove?uid=" + 34 | user.user_id + 35 | "&role=" + 36 | role, 37 | method: "DELETE", 38 | headers: { 39 | Authorization: "Bearer " + idToken, 40 | }, 41 | }) 42 | .then(() => refreshToken()) 43 | .then(() => setLoading(false)); 44 | }; 45 | return ( 46 |
47 |
48 | {loading ? ( 49 |
ReAuthenticating...
50 | ) : ( 51 | <> 52 | 53 |
54 |
55 | {isSeller ? ( 56 | 63 | ) : ( 64 | <> 65 | 72 | 73 | )} 74 |
75 | 76 | )} 77 |
78 |
79 | ); 80 | }; 81 | 82 | export default RoleManager; 83 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/components/roles/roles.js: -------------------------------------------------------------------------------- 1 | import { useAuth } from "contexts/useAuth"; 2 | 3 | const Roles = () => { 4 | const { roles } = useAuth(); 5 | 6 | return ( 7 | <> 8 | {roles && ( 9 |
10 | User Roles 11 | 12 | {roles && 13 | roles.map((val, key) => ( 14 | 15 | {val} 16 | 17 | ))} 18 | 19 |
20 | )} 21 | 22 | ); 23 | }; 24 | 25 | export default Roles; 26 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/config/firebase-config.js: -------------------------------------------------------------------------------- 1 | import { initializeApp } from "firebase/app"; 2 | 3 | const config = { 4 | apiKey: process.env.NEXT_PUBLIC_API_KEY, 5 | authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN, 6 | databaseURL: process.env.NEXT_PUBLIC_DB_URL, 7 | projectId: process.env.NEXT_PUBLIC_PROJECT_ID, 8 | appId: process.env.NEXT_PUBLIC_APP_ID, 9 | }; 10 | 11 | const firebaseApp = initializeApp(config); 12 | 13 | export default firebaseApp; 14 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/contexts/auth.reducer.js: -------------------------------------------------------------------------------- 1 | export const RESET_AUTH_STATE = "RESET_AUTH_STATE"; 2 | 3 | export const initialState = { 4 | user: null, 5 | idToken: null, 6 | roles: null, 7 | isSuper: false, 8 | isSeller: false, 9 | loadingUser: true, 10 | }; 11 | 12 | export const authReducer = (state, action) => { 13 | switch (action.type) { 14 | case RESET_AUTH_STATE: 15 | return { 16 | ...state, 17 | user: action.payload.user ? action.payload.user : initialState.user, 18 | idToken: action.payload.idToken, 19 | roles: action.payload.roles, 20 | isSuper: action.payload.isSuper, 21 | isSeller: action.payload.isSeller, 22 | loadingUser: false, 23 | }; 24 | default: 25 | return state; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/contexts/useAuth.js: -------------------------------------------------------------------------------- 1 | import { useReducer, useEffect, createContext, useContext } from "react"; 2 | import { initialState, authReducer, RESET_AUTH_STATE } from "./auth.reducer"; 3 | import { 4 | getAuth, 5 | signInWithPopup, 6 | GoogleAuthProvider, 7 | signOut, 8 | } from "firebase/auth"; 9 | import firebaseApp from "config/firebase-config"; 10 | 11 | export const UserContext = createContext(); 12 | 13 | const UserProvider = ({ children }) => { 14 | const [state, dispatch] = useReducer(authReducer, initialState); 15 | 16 | useEffect(() => { 17 | const unsubscriber = getAuth(firebaseApp).onAuthStateChanged( 18 | async (user) => { 19 | if (user) { 20 | resetAuth(); 21 | } else { 22 | dispatch({ 23 | type: RESET_AUTH_STATE, 24 | payload: { 25 | loading: false, 26 | }, 27 | }); 28 | } 29 | } 30 | ); 31 | return () => unsubscriber(); 32 | }, []); 33 | 34 | const hasRole = (role) => state.roles.includes(role); 35 | 36 | const extractRoles = (claims) => 37 | Object.keys(claims).filter((claim) => claim.includes("ROLE_")); 38 | 39 | // Login 40 | const login = () => 41 | signInWithPopup(getAuth(firebaseApp), new GoogleAuthProvider()); 42 | 43 | // Logout 44 | const logout = () => signOut(getAuth(firebaseApp)); 45 | 46 | const refreshToken = () => { 47 | getAuth(firebaseApp) 48 | .currentUser.getIdToken(true) 49 | .then((idToken) => resetAuth(idToken)) 50 | .catch((error) => console.error(error)); 51 | }; 52 | 53 | const resetAuth = () => { 54 | getAuth(firebaseApp) 55 | .currentUser.getIdTokenResult() 56 | .then((idTokenResult) => { 57 | if (typeof idTokenResult.claims != undefined) { 58 | const roles = extractRoles(idTokenResult.claims); 59 | dispatch({ 60 | type: RESET_AUTH_STATE, 61 | payload: { 62 | user: idTokenResult.claims, 63 | idToken: idTokenResult.token, 64 | roles, 65 | isSuper: roles.includes("ROLE_SUPER"), 66 | isSeller: roles.includes("ROLE_SELLER"), 67 | }, 68 | }); 69 | } 70 | }) 71 | .catch((error) => console.error(error)); 72 | }; 73 | return ( 74 | 88 | {children} 89 | 90 | ); 91 | }; 92 | 93 | export default UserProvider; 94 | export const useAuth = () => useContext(UserContext); 95 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/pages/_app.js: -------------------------------------------------------------------------------- 1 | import UserProvider from "contexts/useAuth"; 2 | import "../../styles.css"; 3 | 4 | const MyApp = ({ Component, pageProps }) => { 5 | return ( 6 | 7 | 8 | 9 | ); 10 | }; 11 | 12 | export default MyApp; 13 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/src/pages/index.js: -------------------------------------------------------------------------------- 1 | import { useAuth } from "contexts/useAuth"; 2 | import Navbar from "components/navbar"; 3 | import Demo from "components/data/demo"; 4 | import RolesView from "components/rolemanager/rolemanager"; 5 | 6 | const Index = () => { 7 | const { loadingUser, user, isSeller, isSuper } = useAuth(); 8 | 9 | return ( 10 |
11 | {loadingUser ? ( 12 |

Authenticating

13 | ) : ( 14 |
15 | 16 |
17 | {user && ( 18 | <> 19 | 20 |
21 | 22 | )} 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | {isSeller ? ( 36 | 37 | ) : ( 38 | <> 39 | 42 | 43 | 44 | 45 | )} 46 | 47 | 48 | 49 | {isSuper ? ( 50 | 51 | ) : ( 52 | <> 53 | 56 | 57 | 58 | 59 | )} 60 | 61 | 62 |
Public Data
Protected Data
Seller Data 40 | Component Visible only to Sellers 41 |
Super Data 54 | Component Visible only to Super Admins 55 |
63 |
64 |
65 | )} 66 |
67 | ); 68 | }; 69 | 70 | export default Index; 71 | -------------------------------------------------------------------------------- /ui-client-side-session-demo/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font: 15px Helvetica, Arial, sans-serif; 3 | display: flex; 4 | flex-direction: row; 5 | justify-content: center; 6 | } 7 | table { 8 | width: 100%; 9 | border-collapse: collapse; 10 | } 11 | tr { 12 | border-bottom: 1px solid #ced4da; 13 | } 14 | .container { 15 | display: flex; 16 | flex-direction: column; 17 | flex-wrap: wrap; 18 | max-width: 750px; 19 | } 20 | .data { 21 | height: 100px; 22 | max-width: 355px; 23 | } 24 | .label { 25 | font-size: 18px; 26 | font-weight: 700; 27 | margin-bottom: 10px; 28 | color: #00509d; 29 | width: 160px; 30 | } 31 | .status { 32 | font-size: 14px; 33 | font-weight: 500; 34 | padding: 1px 6px; 35 | margin: 0px 10px; 36 | border-radius: 5px; 37 | color: white; 38 | } 39 | .message { 40 | margin: 10px 5px; 41 | font-size: 18px; 42 | } 43 | .path { 44 | color: #6c757d; 45 | font-size: 16px; 46 | font-weight: 500; 47 | font-style: italic; 48 | text-decoration: underline; 49 | margin: 0px 10px; 50 | } 51 | .card { 52 | border: 1px solid #ced4da; 53 | margin: 30px 0px; 54 | padding: 10px 10px 0px 10px; 55 | border-radius: 2px; 56 | } 57 | .button { 58 | border-radius: 2px; 59 | border-width: 0px; 60 | padding: 5px 10px; 61 | font-weight: 700; 62 | font-size: 16px; 63 | cursor: pointer; 64 | } 65 | .primary { 66 | background: #06d6a0; 67 | color: #ffffff; 68 | } 69 | .secondary { 70 | background: #adb5bd; 71 | color: #000000; 72 | } 73 | .navbar { 74 | display: flex; 75 | flex-direction: row; 76 | justify-content: space-between; 77 | align-items: center; 78 | } 79 | .role { 80 | font-size: 12px; 81 | font-weight: 700; 82 | padding: 2px 5px; 83 | margin: 0px 10px; 84 | border-radius: 2px; 85 | color: black; 86 | background-color: #ffd23f; 87 | border: 1px solid #ffd23f; 88 | } 89 | 90 | .access-closed { 91 | display: flex; 92 | flex-direction: row; 93 | align-items: center; 94 | font-weight: 900; 95 | font-size: 18px; 96 | color: #d90429; 97 | width: 500px !important; 98 | } 99 | .user-nav-section { 100 | display: flex; 101 | flex-direction: column; 102 | } 103 | .user-info { 104 | display: flex; 105 | flex-direction: row-reverse; 106 | justify-content: center; 107 | align-items: center; 108 | } 109 | .avatar { 110 | width: 40px; 111 | height: 40px; 112 | border-radius: 5px; 113 | } 114 | .name { 115 | font-weight: 700; 116 | color: grey; 117 | margin-right: 5px; 118 | color: #06d6a0; 119 | } 120 | .logout-section { 121 | display: flex; 122 | flex-direction: row-reverse; 123 | margin: 10px 0px; 124 | } 125 | 126 | .roles-container { 127 | display: flex; 128 | flex-direction: row; 129 | justify-content: space-between; 130 | } 131 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/.env.sample: -------------------------------------------------------------------------------- 1 | NEXT_PUBLIC_API_KEY= 2 | NEXT_PUBLIC_AUTH_DOMAIN= 3 | NEXT_PUBLIC_DB_URL= 4 | NEXT_PUBLIC_PROJECT_ID= 5 | NEXT_PUBLIC_APP_ID= 6 | NEXT_PUBLIC_MIDDLEWARE_URL= 7 | NEXT_PUBLIC_TEST_LOGIN= -------------------------------------------------------------------------------- /ui-server-side-session-demo/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env 29 | .env.local 30 | .env.development.local 31 | .env.test.local 32 | .env.production.local 33 | 34 | # vercel 35 | .vercel 36 | 37 | yarn.lock -------------------------------------------------------------------------------- /ui-server-side-session-demo/README.md: -------------------------------------------------------------------------------- 1 | # Nextjs Demo using Server side Firebase session 2 | 3 | ## Installation 4 | 5 | Add .env file in the project root folder with values from firebase config json and spring boot host and port 6 | 7 | ``` 8 | NEXT_PUBLIC_API_KEY=REPLACE_WITH_API_KEY 9 | NEXT_PUBLIC_AUTH_DOMAIN=REPLACE_WITH_AUTH_DOMAIN 10 | NEXT_PUBLIC_DB_URL=REPLACE_WITH_DB_URL 11 | NEXT_PUBLIC_PROJECT_ID=REPLACE_WITH_PROJECT_ID 12 | NEXT_PUBLIC_APP_ID=REPLACE_WITH_APP_ID 13 | NEXT_PUBLIC_MIDDLEWARE_URL=REPLACE_WITH_SPRING_BOOT_URL 14 | NEXT_PUBLIC_TEST_LOGIN=false 15 | ``` 16 | 17 | First, run the development server: 18 | 19 | ```bash 20 | npm run dev 21 | # or 22 | yarn dev 23 | ``` 24 | 25 | cypress end to end test 26 | 27 | ```bash 28 | npm run it 29 | # or 30 | yarn it 31 | ``` 32 | 33 | Open [http://localhost:4000](http://localhost:4000) with your browser to see the result. 34 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress.json: -------------------------------------------------------------------------------- 1 | { 2 | "baseUrl": "https://demo.dev", 3 | "requestTimeout": 6000, 4 | "env": { 5 | "api_url": "https://api.demo.dev" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/fixtures/test-users.js: -------------------------------------------------------------------------------- 1 | export const testUsers = { 2 | "johnwick@online.com": { 3 | uid: 3, 4 | name: "John Wick", 5 | isSuper: false, 6 | email: "johnwick@online.com", 7 | }, 8 | "jakeperalta@online.com": { 9 | uid: 4, 10 | name: "jake peralta", 11 | isSuper: false, 12 | email: "jakeperalta@online.com", 13 | }, 14 | "superman@online.com": { 15 | uid: 5, 16 | name: "super man", 17 | isSuper: true, 18 | email: "superman@online.com", 19 | }, 20 | }; 21 | 22 | export const findUserByEmail = (email) => { 23 | return testUsers[email]; 24 | }; 25 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/helpers/index.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-server-side-session-demo/cypress/helpers/index.js -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/integration/examples/auth.spec.js: -------------------------------------------------------------------------------- 1 | /// 2 | import { findUserByEmail } from "../../fixtures/test-users"; 3 | 4 | const TEST_USER_EMAIL = "johnwick@online.com"; 5 | const testUser = findUserByEmail(TEST_USER_EMAIL); 6 | 7 | context("Authentication Test", () => { 8 | before(() => { 9 | cy.visit("/"); 10 | }); 11 | 12 | beforeEach(() => { 13 | Cypress.Cookies.preserveOnce("authenticated", "session", "fullname"); 14 | }); 15 | 16 | it("Login successful", () => { 17 | cy.get("[data-testid=test-login-user]").type(TEST_USER_EMAIL); 18 | cy.intercept( 19 | "POST", 20 | Cypress.env("api_url") + "/test/login/" + TEST_USER_EMAIL 21 | ).as("testLogin"); 22 | cy.get("[data-testid=test-login-submit]").click(); 23 | cy.wait(["@testLogin"]).then((interception) => { 24 | if (interception.responseWaited) { 25 | cy.wait(4000); 26 | cy.getCookie("session").should("exist"); 27 | cy.getCookie("authenticated").should("have.property", "value", "true"); 28 | cy.getCookie("fullname").should( 29 | "have.property", 30 | "value", 31 | testUser.name.split(" ").join("_").toLowerCase() 32 | ); 33 | 34 | cy.get("[data-testid=authenticated-user-fullname]").should( 35 | "be.visible" 36 | ); 37 | cy.get("[data-testid=authenticated-user-fullname]").should( 38 | "have.text", 39 | testUser.name.toLowerCase() 40 | ); 41 | } 42 | }); 43 | }); 44 | 45 | it("Logout successful", () => { 46 | cy.get("[data-testid=logout]").click(); 47 | cy.getCookie("session").should("not.exist"); 48 | cy.getCookie("authenticated").should("not.exist"); 49 | cy.get("[data-testid=login-with-google]").should("be.visible"); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/plugins/index.js: -------------------------------------------------------------------------------- 1 | /// 2 | // *********************************************************** 3 | // This example plugins/index.js can be used to load plugins 4 | // 5 | // You can change the location of this file or turn off loading 6 | // the plugins file with the 'pluginsFile' configuration option. 7 | // 8 | // You can read more here: 9 | // https://on.cypress.io/plugins-guide 10 | // *********************************************************** 11 | 12 | // This function is called when a project is opened or re-opened (e.g. due to 13 | // the project's config changing) 14 | 15 | /** 16 | * @type {Cypress.PluginConfig} 17 | */ 18 | module.exports = (on, config) => { 19 | // `on` is used to hook into various events Cypress emits 20 | // `config` is the resolved Cypress config 21 | } 22 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/support/commands.js: -------------------------------------------------------------------------------- 1 | // *********************************************** 2 | // This example commands.js shows you how to 3 | // create various custom commands and overwrite 4 | // existing commands. 5 | // 6 | // For more comprehensive examples of custom 7 | // commands please read more here: 8 | // https://on.cypress.io/custom-commands 9 | // *********************************************** 10 | // 11 | // 12 | // -- This is a parent command -- 13 | // Cypress.Commands.add("login", (email, password) => { ... }) 14 | // 15 | // 16 | // -- This is a child command -- 17 | // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) 18 | // 19 | // 20 | // -- This is a dual command -- 21 | // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) 22 | // 23 | // 24 | // -- This will overwrite an existing command -- 25 | // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) 26 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/cypress/support/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example support/index.js is processed and 3 | // loaded automatically before your test files. 4 | // 5 | // This is a great place to put global configuration and 6 | // behavior that modifies Cypress. 7 | // 8 | // You can change the location of this file or turn off 9 | // automatically serving support files with the 10 | // 'supportFile' configuration option. 11 | // 12 | // You can read more here: 13 | // https://on.cypress.io/configuration 14 | // *********************************************************** 15 | 16 | // Import commands.js using ES2015 syntax: 17 | import './commands' 18 | 19 | // Alternatively you can use CommonJS syntax: 20 | // require('./commands') 21 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./src" 4 | }, 5 | "exclude": ["node_modules"] 6 | } 7 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "firebase-ui", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev -p 4000", 7 | "build": "next build", 8 | "start": "next start", 9 | "it": " ./node_modules/.bin/cypress open" 10 | }, 11 | "dependencies": { 12 | "axios": "^0.21.4", 13 | "firebase": "^9.0.2", 14 | "js-cookie": "^3.0.1", 15 | "next": "^11.1.2", 16 | "react": "^17.0.2", 17 | "react-dom": "^17.0.2" 18 | }, 19 | "devDependencies": { 20 | "cypress": "^8.4.1" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-server-side-session-demo/public/favicon.ico -------------------------------------------------------------------------------- /ui-server-side-session-demo/public/vercel.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/screenshots/cypress_auth_test.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-server-side-session-demo/screenshots/cypress_auth_test.gif -------------------------------------------------------------------------------- /ui-server-side-session-demo/screenshots/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gladius/firebase-spring-boot-rest-api-authentication/1cf8f06ccad1694616d78d2e4321f455d012077c/ui-server-side-session-demo/screenshots/screenshot.png -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/components/auth/firebase.auth.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import { getAuth, signInWithCustomToken } from "firebase/auth"; 3 | import firebase from "config/firebase.config"; 4 | 5 | export const backendLogin = async (idToken, user) => { 6 | return axios({ 7 | url: process.env.NEXT_PUBLIC_MIDDLEWARE_URL + "/session/login", 8 | method: "POST", 9 | headers: { 10 | "Content-Type": "application/json", 11 | Authorization: "Bearer " + idToken, 12 | }, 13 | data: { provider: "GOOGLE" }, 14 | withCredentials: true, 15 | }) 16 | .then((res) => { 17 | return Promise.resolve({ success: true, user }); 18 | }) 19 | .catch((error) => { 20 | return Promise.reject(error); 21 | }); 22 | }; 23 | 24 | export const testLogin = async (testId) => { 25 | return axios({ 26 | url: process.env.NEXT_PUBLIC_MIDDLEWARE_URL + `/test/login/${testId}`, 27 | method: "POST", 28 | headers: { 29 | "Content-Type": "application/json", 30 | }, 31 | }) 32 | .then((res) => { 33 | return signInWithCustomToken(getAuth(firebase), res.data) 34 | .then(async (resp) => { 35 | return await resp.user.getIdToken().then((idToken) => { 36 | return Promise.resolve(backendLogin(idToken)); 37 | }); 38 | }) 39 | .catch((error) => { 40 | return Promise.reject(error); 41 | }); 42 | }) 43 | .catch((error) => { 44 | return Promise.reject(error); 45 | }); 46 | }; 47 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/components/auth/google.svg.js: -------------------------------------------------------------------------------- 1 | const Google = (props) => { 2 | const { color, size, ...otherProps } = props; 3 | return ( 4 | 12 | 13 | 17 | 21 | 25 | 29 | 30 | ); 31 | }; 32 | 33 | export default Google; 34 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/components/auth/login.js: -------------------------------------------------------------------------------- 1 | import GoogleSVG from "./google.svg"; 2 | import { useState } from "react"; 3 | import { testLogin, backendLogin } from "./firebase.auth"; 4 | import { 5 | getAuth, 6 | setPersistence, 7 | inMemoryPersistence, 8 | signInWithPopup, 9 | GoogleAuthProvider, 10 | } from "firebase/auth"; 11 | import { useAuth } from "contexts/useAuth"; 12 | import firebase from "config/firebase.config"; 13 | 14 | const LoginModal = ({}) => { 15 | const [loading, setLoading] = useState(null); 16 | const [testId, setTestId] = useState(""); 17 | const { refreshAuthContext } = useAuth(); 18 | const authenticateUser = () => { 19 | setLoading("Authenticating"); 20 | const auth = getAuth(firebase); 21 | setPersistence(auth, inMemoryPersistence).then(() => { 22 | signInWithPopup(auth, new GoogleAuthProvider()).then(async (result) => { 23 | if (result.user) { 24 | result.user.getIdToken().then((idToken) => { 25 | backendLogin(idToken, result.user).then((response) => 26 | refreshAuthContext() 27 | ); 28 | }); 29 | } 30 | }); 31 | }); 32 | }; 33 | return ( 34 |
35 | {!loading ? ( 36 | <> 37 | 47 | {process.env.NEXT_PUBLIC_TEST_LOGIN == "true" && ( 48 |
49 | setTestId(e.target.value)} 53 | /> 54 | 66 |
67 | )} 68 | 69 | ) : ( 70 |
{loading}
71 | )} 72 |
73 | ); 74 | }; 75 | 76 | export default LoginModal; 77 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/components/auth/public-pages.js: -------------------------------------------------------------------------------- 1 | export default ["/_error", "/"]; 2 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/config/firebase.config.js: -------------------------------------------------------------------------------- 1 | import { initializeApp } from "firebase/app"; 2 | 3 | const config = { 4 | apiKey: process.env.NEXT_PUBLIC_API_KEY, 5 | authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN, 6 | databaseURL: process.env.NEXT_PUBLIC_DB_URL, 7 | projectId: process.env.NEXT_PUBLIC_PROJECT_ID, 8 | appId: process.env.NEXT_PUBLIC_APP_ID, 9 | }; 10 | 11 | const firebaseApp = initializeApp(config); 12 | 13 | export default firebaseApp; 14 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/contexts/useAuth.js: -------------------------------------------------------------------------------- 1 | import { createContext, useContext, useEffect, useReducer } from "react"; 2 | import Cookies from "js-cookie"; 3 | import Router from "next/router"; 4 | import publicPages from "components/auth/public-pages"; 5 | import axios from "axios"; 6 | 7 | export const AuthContext = createContext(); 8 | const RESET_USER_STATE = "RESET_USER_STATE"; 9 | 10 | const initialState = { 11 | isLoading: true, 12 | isAuthenticated: false, 13 | pic: null, 14 | fullname: null, 15 | }; 16 | 17 | const userReducer = (state, action) => { 18 | switch (action.type) { 19 | case RESET_USER_STATE: 20 | const appCookies = action.payload; 21 | return { 22 | ...state, 23 | isAuthenticated: appCookies.authenticated, 24 | pic: appCookies.pic, 25 | fullname: 26 | appCookies.fullname && appCookies.fullname.split("_").join(" "), 27 | isLoading: false, 28 | }; 29 | default: 30 | return state; 31 | } 32 | }; 33 | 34 | export const AuthProvider = (props) => { 35 | const [state, dispatch] = useReducer(userReducer, initialState); 36 | 37 | useEffect(() => { 38 | refreshAuthContext(); 39 | }, []); 40 | 41 | useEffect(() => { 42 | if (!state.isLoading) { 43 | const path = props.appProps.router.route; 44 | if ( 45 | path != "/" && 46 | !state.isAuthenticated && 47 | !publicPages.includes(path) 48 | ) { 49 | Router.push("/"); 50 | } 51 | } 52 | }, [state.isAuthenticated, state.isLoading]); 53 | 54 | const refreshAuthContext = () => { 55 | dispatch({ type: RESET_USER_STATE, payload: Cookies.get() }); 56 | }; 57 | 58 | const logout = () => { 59 | axios({ 60 | url: process.env.NEXT_PUBLIC_MIDDLEWARE_URL + "/session/logout", 61 | method: "POST", 62 | headers: { 63 | "Content-Type": "application/json", 64 | }, 65 | withCredentials: true, 66 | }).then((res) => { 67 | refreshAuthContext(); 68 | }); 69 | }; 70 | 71 | return ( 72 | 82 | {props.children} 83 | 84 | ); 85 | }; 86 | 87 | export const useAuth = () => { 88 | return useContext(AuthContext); 89 | }; 90 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/pages/_app.js: -------------------------------------------------------------------------------- 1 | import "styles/globals.css"; 2 | import { AuthProvider } from "contexts/useAuth"; 3 | 4 | function MyApp(props) { 5 | const { Component, pageProps } = props; 6 | 7 | return ( 8 | 9 | 10 | 11 | ); 12 | } 13 | 14 | export default MyApp; 15 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/pages/index.js: -------------------------------------------------------------------------------- 1 | import Head from "next/head"; 2 | import Login from "components/auth/login"; 3 | import { useAuth } from "contexts/useAuth"; 4 | 5 | const Home = () => { 6 | const { isAuthenticated, fullname, pic, logout } = useAuth(); 7 | return ( 8 |
9 | 10 | Server Side Session 11 | 12 | 13 | 14 |
15 |
16 |

Server Side Session

{" "} 17 | {isAuthenticated && ( 18 | 19 | 26 | 27 | )} 28 |
29 | 30 | {isAuthenticated ? ( 31 |
32 | {pic && } 33 | 34 | {fullname} 35 | 36 |
37 | ) : ( 38 |
39 | 40 |
41 | )} 42 |
43 |
44 | ); 45 | }; 46 | export default Home; 47 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/pages/profile.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProfilePage = () => { 4 | return
Profile Page
; 5 | }; 6 | 7 | export default ProfilePage; 8 | -------------------------------------------------------------------------------- /ui-server-side-session-demo/src/styles/globals.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | padding: 0; 4 | margin: 0; 5 | font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, 6 | Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; 7 | } 8 | 9 | a { 10 | color: inherit; 11 | text-decoration: none; 12 | } 13 | 14 | * { 15 | box-sizing: border-box; 16 | } 17 | 18 | button { 19 | border-radius: 5px; 20 | border-width: 0px; 21 | padding: 5px 10px; 22 | font-weight: 500; 23 | font-size: 20px; 24 | cursor: pointer; 25 | display: flex; 26 | flex-direction: row; 27 | justify-content: center; 28 | align-items: center; 29 | } 30 | 31 | .button-google { 32 | border: 1px solid #e5e5e5; 33 | background-color: #ffffff; 34 | } 35 | 36 | .button-logout { 37 | border: 1px solid #e5e5e5; 38 | color: #ffffff; 39 | background-color: black; 40 | } 41 | .button-test { 42 | border: 1px solid #ffffff; 43 | color: #ffffff; 44 | background-color: #ffffff; 45 | } 46 | 47 | .button-icon { 48 | margin: 0px 10px; 49 | } 50 | 51 | .container { 52 | min-height: 100vh; 53 | padding: 0 0.5rem; 54 | display: flex; 55 | flex-direction: column; 56 | justify-content: center; 57 | align-items: center; 58 | } 59 | 60 | .name { 61 | text-transform: capitalize; 62 | color: #0091ad; 63 | font-size: 25px; 64 | } 65 | .avatar { 66 | width: 80px; 67 | height: 80px; 68 | border-radius: 10px; 69 | } 70 | .profile-container { 71 | display: flex; 72 | flex-direction: row; 73 | width: 400px; 74 | justify-content: space-around; 75 | align-items: center; 76 | border: 1px solid #e5e5e5; 77 | padding: 10px 20px; 78 | border-radius: 10px; 79 | } 80 | 81 | .title-card { 82 | display: flex; 83 | flex-direction: row; 84 | width: 400px; 85 | justify-content: space-around; 86 | align-items: center; 87 | margin-bottom: 50px; 88 | } 89 | .login-container { 90 | display: flex; 91 | flex-direction: row; 92 | width: 400px; 93 | justify-content: space-around; 94 | align-items: center; 95 | } 96 | .test-login-container { 97 | display: flex; 98 | flex-direction: row; 99 | margin: 20px 0px; 100 | } 101 | --------------------------------------------------------------------------------