1. Auth
Authenticate is a very familiar thing of each app, in this article I will introduce the auth module for nuxt to help you handle this job very quickly and easily.
2. Installation
First of all, install nuxt
yarn create nuxt-app nuxt-project
Install auth module
yarn add @nuxtjs/auth yarn add @nuxtjs/axios
add the module to nuxt.config.js
1 2 3 4 5 | modules: [ '@nuxtjs/axios', '@nuxtjs/auth' ], |
add the file index.js
to the store
directory to active vuex for the project
Run the yarn dev
command and open the link
Now let’s try adding the middleware to the pages / index.vue file
1 2 3 4 | export default { middleware: 'auth' } |
and the result is
Since we have set the auth middleware but have not authenticated the user, nuxt has redirecrt us to the /login
page. Now we will continue to create the pages / login / index.vue file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <template> <button class="login"> Login with Google </button> </template> <script> </script> <style lang="scss" scoped> .login { box-sizing: border-box; position: relative; margin: 0.2em; padding: 0 15px 0 46px; border: none; text-align: left; line-height: 34px; white-space: nowrap; border-radius: 0.2em; font-size: 16px; color: #FFF; background: #DD4B39; &:before { content: ""; box-sizing: border-box; position: absolute; top: 0; left: 0; width: 34px; height: 100%; border-right: #BB3F30 1px solid; background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png') 6px 6px no-repeat; } &:focus { outline: none; background: #E74B37; } &:active { box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1); } &:hover { cursor: pointer; } } </style> |
Next we need to create google clientId https://console.developers.google.com/ details then google will have a lot of instructions. Add clientId both created and added to nuxt.config.js
1 2 3 4 5 6 7 8 | auth: { strategies: { google: { client_id: '...' }, } } |
Modify the login / index.vue file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <template> <button class="login" @click="login"> Login with Google </button> </template> <script> export default { methods: { login() { this.$auth.loginWith('google', { params: { prompt: "select_account" } }) } } } </script> ... |
Revise the pages / index.vue file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <template> <div class="container"> <img :src="user.picture" alt=""> <p>{{ user.name }}</p> </div> </template> <script> export default { middleware: 'auth', computed: { user() { return this.$auth.user; } } } </script> <style> </style> |
Now open your browser, login and see the results