Home Web Front-end JS Tutorial vue+springboot separates single point cross-domain login between front and back ends

vue+springboot separates single point cross-domain login between front and back ends

Apr 13, 2018 am 10:23 AM
Log in

This time I will bring you vue springboot front-end and back-end separation single point cross-domain login, vue springboot front-end and front-end separation single point cross-domain login What are the precautions, the following is a practical case, Let’s take a look.

Recently I am working on a back-end management system. The front-end uses the popular vue.js, and the back-end is based on springboot. Because the backend system does not have a login function, but the company requires unified login, the login authentication uses the authentication system of the .net project team. That means doing single sign-on. As for students who don’t know what single sign-on is, I suggest you go to the all-purpose Du Niang.

When I first received this requirement, I thought with disdain: Just logging in is not important. However, the development process slapped me hard (a hot slap). . . , so I must record this lesson carefully this time to avoid stepping into such pitfalls in the future.

The first problem I faced was cross-domain. The browser console directly reported CORS. With my many years of development experience, I decisively configured the cross-domain configuration in the background. The code is as follows:

@Configuration
public class CorsConfiguration {
 @Bean
 public WebMvcConfigurer corsConfigurer() {
  return new WebMvcConfigurerAdapter() {
   @Override
   public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
      .allowedHeaders("*")
      .allowedMethods("*")
      .allowedOrigins("*");
   }
  };
 }
}
Copy after login

This configuration allows all mappings, all request headers, all request methods, and all sources. After changing the configuration, I decisively restarted the project to see the effect. I found that there was no way to redirect to the single sign-in page. Seeing that the browser error was caused by cross-domain, I first uploaded the code of my login interceptor

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 //用户已经登录
 if (request.getSession().getAttribute("user") != null) {
  return true;
 }
 //从单点登录返回之后的状态,本系统还不处于登录状态
 //根据code值去获取access_token,然后再根据access_token去获取用户信息,并将用户信息存到session中
 String state = request.getParameter("state");
 String uri = getUri(request);
 if (isLoginFromSSO(state)) {
  String code = request.getParameter("code");
  Object cacheUrl = request.getSession().getAttribute(state);
  if (cacheUrl == null) {
   response.sendRedirect(uri);
   return false;
  }
  HttpUtil client = new HttpUtil();
  StringBuffer sb = new StringBuffer();
  sb.append("code=").append(code)
    .append("&grant_type=").append("authorization_code")
    .append("&client_id=").append(SSOAuth.ClientID)
    .append("&client_secret=").append(SSOAuth.ClientSecret)
    .append("&redirect_uri=").append(URLEncoder.encode((String) cacheUrl));
  String resp = client.post(SSOAuth.AccessTokenUrl, sb.toString());
  Map<String, String> map = new Gson().fromJson(resp, Map.class);
  //根据access_token去获取用户信息
  String accessToken = map.get("access_token");
  HttpUtil http = new HttpUtil();
  http.addHeader("Authorization", "Bearer " + accessToken);
  String encrypt = http.get(SSOAuth.UserUrl);
  String userinfo = decryptUserInfo(encrypt);
  //封装成user对象
  User user = new Gson().fromJson(userinfo, User.class);
  request.getSession().setAttribute("user", user);
  return true;
 }
 //跳转到单点登录界面
 state = Const._SSO_LOGIN + Const.UNDERLINE + RandomUtil.getUUID();
 request.getSession().setAttribute(state, uri);
 String redirectUrl = buildAuthCodeUrl(uri, state);
 response.sendRedirect(redirectUrl);
 return false;
}
Copy after login

Later, the front-end vue requests the login interface method of the backend directly using

window.location.href=this.$api.config.baseUrl+"/system/user/login"
Copy after login

After the front-end accesses the system, you can jump directly to the single sign-on page. But when I entered my account and password and clicked to log in, I jumped back to the system and found that all request data interfaces could not be accessed normally. Debug found that all requests did not carry user information and were recognized by the interceptor as not logged in, so all requests could not pass. .

Why is it that even though I am logged in, the interceptor also sets user information to the session, why are the cookies gone? I initiated a request again and found that the JsessionId of each request was different. I checked a lot of information and found that I needed to add a configuration that allows authentication information to be added to the front end

axios.defaults.withCredentials=true;
Copy after login

The background also needs to make a corresponding configuration allowCredentials(true);

@Bean
public WebMvcConfigurer corsConfigurer() {
 return new WebMvcConfigurerAdapter() {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
   registry.addMapping("/**")
     .allowedHeaders("*")
     .allowedMethods("*")
     .allowedOrigins("*").allowCredentials(true);
  }
 };
}
Copy after login

After adding this configuration, I ran the operation process again and found that I could jump to the system normally after logging in, and the page data was also displayed normally.

Just when I thought I was done, I suddenly clicked on a page and the data could not be displayed normally. I was so confused. I quickly F12 and found a request method I had never seen before, OPTIONS request. It turned out that this request method was obviously POST. Why did it change? Has it become OPTIONS? So I ordered several other POST requests and found that they all turned into OPTIONS requests. I was confused and quickly checked the information of OPTIONS requests. The Internet said that OPTIONS requests are called "pre-check requests", which means that in your formal Before the request is executed, the browser will first initiate a pre-check request. Only after the pre-check request passes can the formal request be executed. After reading it, I suddenly realized that OPTIONS was intercepted, so I could no longer execute my POST request. Then I just let the pre-check request pass. Just add this judgment to the interceptor

//option预检查,直接通过请求
if ("OPTIONS".equals(request.getMethod())){
 return true;
}
Copy after login

In this way, the interceptor finds that the request is a pre-check request and passes it directly, and then the next POST request can be executed.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Instructions for vue’s project structure

Detailed explanation of vue’s implementation of the small ball parabola effect of the shopping cart

The above is the detailed content of vue+springboot separates single point cross-domain login between front and back ends. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the &quot;Login&quot; button. (2) Select &quot;Retrieve Password&quot;. (3) Enter the mobile phone number you used when registering your account

'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! 'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! Jan 05, 2024 am 10:42 AM

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

How to log in to two devices on Quark How to log in to two devices on Quark Feb 23, 2024 pm 10:55 PM

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the &quot;Login&quot; button and select &quot;Account and Password Login&quot;; 3. Click the &quot;Forgot your password?&quot; button; 4. Enter your account number. Click &quot;Next&quot;; 5. The system will send a verification code to your mobile phone, enter the verification code and click &quot;OK&quot;; 6. Set a new password and confirm. You can also use a third-party account (such as

See all articles