Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use RESTful API to handle authentication through Vue

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use RESTful API to deal with authentication through Vue". In daily operation, I believe many people have doubts about how to use RESTful API to deal with authentication through Vue. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to use RESTful API to deal with authentication through Vue". Next, please follow the editor to study!

Authentication (login!) Is an important part of many websites. Let's take a look at how to use Vue to handle it on a Web site in the same way as it does in any custom backend. Vue can't actually authenticate entirely on its own, so we need another service for that, so we'll use another service (Firebase) for this, and then integrate the entire experience into Vue.

Authentication works in a completely different way on a single-page application (SPA) than on a site that reloads each page.

We will build a user login interface and send the submitted data to the server to check whether the user exists. If so, we will receive a token. This is very useful because it will be used throughout our site to check if users are still logged in. If not, the user can register at any time. In other words, it can be used in many conditional contexts. In addition, if we need any information from the server that needs to be logged in, the token is sent to the server via URL so that the information is sent only to the logged-in user.

A complete demonstration of this tutorial has been posted on GitHub for those who are familiar with reading the code. The rest of us can continue to read this article. The starting file is also on GitHub, so you can continue while we code together.

After downloading, you will run npm install in the terminal. If you want to build this application entirely yourself, you must install Vuex, Vue Router, and axios. We will also use Firebase in this project, so take the time to set up a free account and create a new project in it.

After adding the project to Firebase, go to the authentication section and set the login method, which will use the traditional e-mail / password provider, which will be stored on the Firebase server.

After that, we will go to the Firebase Auth REST API document to get our registration and log in to the API endpoint. We need an API key to use these endpoints in our application, and we can find it in the Firebase project settings.

Firebase provides authentication through SDK, but we use Auth API to demonstrate authentication through any custom back-end server.

In our status report file, there is a registration form below. Because we are focused on learning concepts, we are here to keep things simple.

Mail Your Name Password Submit

If we do not use SPA, we will naturally use axios to send the data to the script tag, as shown below:

Axios.post ('https://identitytoolkit.googleapis.com/v1/account signUpdated key = [API _ KEY]', {email:authData.email, password:authData.password, returnSecureToken:true}) .then (res = > {console.log (res)}) .catch (error = > console.log (error))}}

Register and log in

Using SPA (or Vue in this case) is very different from the above approach. Instead, we will use Vuex to send the authorization request store.js in the operation in the file. We do this because we want the entire application to be aware of any changes in the user authentication status.

Actions: {signup ({commit}, authData) {axios.post ('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]',{ email:authData.email, password:authData.password, returnSecureToken:true}). Then (res = > {console.log (res) router.push ("/ dashboard")}) .catch (error = > console.log (error))}, login ({commit}) AuthData) {axios.post (https://identitytoolkit.googleapis.com/v1/accounts:signIn?key=[API_KEY]',{ email:authData.email, password:authData.password, returnSecureToken:true}) .then (res = > {console.log (res) router.push ("/ dashboard")}) .catch (error = > console.log (error))}}

We can use almost the same thing for the login method, but we can use the login API endpoint instead. Then, we assign the registration and login of the components to their respective operations in the store.

Methods: {onSubmit () {constformData = {email: this.email, name: this.name, password: this.password} this.$store.dispatch ('signup',formData)}

FormData contains the user's data.

Methods: {onSubmit () {const formData = {email: this.email, password: this.password} this.$store.dispatch ('login', {email: formData.email, password: formData.password})}}

We will receive the authentication data (that is, tokens and user ID) received from the registration / login form and use it as the status of the Vuex. The initial result is null.

State: {idToken:null, userId:null, user:null}

Now, in the mutation, we authUser create a new method called a method that stores the data collected from the response. We need to import the router into the store because we need it later.

Import router from'/router' mutations: {authUser (state,userData) {state.idToken = userData.token state.userId = userData.userId}}

Then within the block in the signup / login method of our operation, we commit and save the response to the variation just created by authUser to the local store.

Actions: {signup ({commit}, authData) {axios.post ('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]'),{ email:authData.email, password:authData.password, returnSecureToken:true}). Then (res = > {console.log (res) commit (' authUser', {token:res.data.idToken) UserId:res.data.localId}) localStorage.setItem ('token',res.data.idToken) localStorage.setItem (' userId',res.data.localId) router.push ("/ dashboard")}) .catch (error = > console.log (error))}, login ({commit}, authData) {axios.post ('https://identitytoolkit.googleapis.com/v1/accounts:signIn?key=[API_KEY]'),) {email:authData.email, password:authData.password, returnSecureToken:true}) .then (res = > {console.log (res) commit ('authUser', {token:res.data.idToken, userId:res.data.localId}) localStorage.setItem (' token',res.data.idToken) localStorage.setItem ('userId') Res.data.localId) router.push ("/ dashboard")}) .catch (error = > console.log (error))}}

Set authentication protection

Now that we have stored the token in the application, we will use it when setting up the Auth Guard. What is Auth Guard? It protects dashboards from unauthenticated users from accessing dashboards without tokens.

First, we will enter the route file and import it into the store. Because the token determines the login status of the user, it is imported into the store.

Import store from'./store.js'

So, within our route array, go to the dashboard path, and add the method beforeEnter, which has three parameters: to,from and next. In this approach, we simply say that if the token is stored (if authenticated, the token will be completed automatically), then next means that the token will continue along the specified path. Otherwise, we will bring unauthenticated users back to the registration page.

{path:'/dashboard', component:DashboardPage, beforeEnter (to,from, next) {if (store.state.idToken) {next ()} else {next ('/ signin')}

Create UI statu

At this point, whether we log in or not, we can still see the dashboard in the navigation, which is not what we want. We must add another method under the called getters, which ifAuthenticated checks to see if the token in the state is null, and then updates the navigation entry accordingly.

Getters: {user (state) {returnstate.user}, ifAuthenticated (state) {returnstate.idToken! = = null}}

Next, let's open the title component and auth to create a method inside the computed property. This will be distributed to the getter we just created in the store at ifAuthenticated. If there is no token, ifAuthenticated will return false, which automatically means that auth will also be null, and vice versa. After that, we added a v-if check to determine whether the dashboard options are displayed in the navigation if the auth is null or not.

Vue Authenticate Dashboard Register Log In exportdefault {computed: {auth () {returnthis.$store.getters.ifAuthenticated}},}

Write off

What is an application that does not have a logout button? Let's create a new mutation named clearAuth, which sets both tokens and userId to null.

Mutations: {authUser (state,userData) {state.idToken = userData.token state.userId = userData.userId}, clearAuth (state) {state.idToken = null state.userId = null}}

Then, in our logout operation, we promised to clearAuth, delete the local storage and add router.replace ('/') to redirect the user correctly after logging out.

Return to the title component. We have an onLogout method that allows logout to schedule our actions in the store. Then, we add @ click to the button, which calls the onLogout method, as follows:

Vue Authenticate Dashboard Register Log In Log Out exportdefault {computed: {auth () {returnthis.$store.getters.ifAuthenticated}} Methods: {onLogout () {this.$store.dispatch ('logout')}

Automatic login? That's for sure!

Our application is almost complete. We can register, log in, and log out using all the UI changes we just made. However, when we refresh the application, we lose data and log out, and we have to start over because we store tokens and ID in JavaScript's Vuex. This means that after refreshing, everything in the application is reloaded into the browser.

What we need to do is retrieve the token in the local store. In this way, whenever the window is refreshed, we can have the user's token in the browser, as long as the token is still valid, we can even automatically log in to the user.

Create a new action method called so that we can userId get tokens from local storage only if the user has an AutoLogin token. We then submit the data to the method in the authUser mutation.

Actions: {AutoLogin ({commit}) {const token = localStorage.getItem ('token') if (! token) {return} constuserId = localStorage.getItem (' userId') const token = localStorage.getItem ('token') commit (' authUser', {idToken: token, userId:userId})}

Then we go to our App.vue 's created method and distribute it from the store when autoLogin loads the application.

Created () {this.$store.dispatch ('AutoLogin')}

That's great! In this way, we can successfully implement authentication within the application, and we can now use to deploy npm run build. Watch the live demonstration to see the actual operation.

At this point, the study on "how to use RESTful API to handle authentication through Vue" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report