国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 詳解前后端分離之Java后端

詳解前后端分離之Java后端

2020-10-27 16:51root__1024 Java教程

這篇文章主要介紹了詳解前后端分離之Java后端,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

前后端分離的思想由來已久,不妨嘗試一下,從上手開始,先把代碼寫出來再究細節。

代碼下載:https://github.com/jimolonely/AuthServer

前言

以前服務端為什么能識別用戶呢?對,是session,每個session都存在服務端,瀏覽器每次請求都帶著sessionId(就是一個字符串),于是服務器根據這個sessionId就知道是哪個用戶了。
那么問題來了,用戶很多時,服務器壓力很大,如果采用分布式存儲session,又可能會出現不同步問題,那么前后端分離就很好的解決了這個問題。

前后端分離思想:
在用戶第一次登錄成功后,服務端返回一個token回來,這個token是根據userId進行加密的,密鑰只有服務器知道,然后瀏覽器每次請求都把這個token放在Header里請求,這樣服務器只需進行簡單的解密就知道是哪個用戶了。這樣服務器就能專心處理業務,用戶多了就加機器。當然,如果非要討論安全性,那又有說不完的話題了。

下面通過SpringBoot框架搭建一個后臺,進行token構建。

構建springboot項目

我的目錄結構:(結果未按標準書寫,僅作說明)

詳解前后端分離之Java后端

不管用什么IDE,最后我們只看pom.xml里的依賴:

為了盡可能簡單,就不連數據庫了,登陸時用固定的。

devtools:用于修改代碼后自動重啟;

jjwt:加密這么麻煩的事情可以用現成的,查看https://github.com/jwtk/jjwt

?
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
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 
    <!-- JJWT -->
    <dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.6.0</version>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

登錄

這里的加密密鑰是:base64EncodedSecretKey

?
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
import java.util.Date;
 
import javax.servlet.ServletException;
 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
 
@RestController
@RequestMapping("/")
public class HomeController {
 
  @PostMapping("/login")
  public String login(@RequestParam("username") String name, @RequestParam("password") String pass)
      throws ServletException {
    String token = "";
    if (!"admin".equals(name)) {
      throw new ServletException("找不到該用戶");
    }
    if (!"1234".equals(pass)) {
      throw new ServletException("密碼錯誤");
    }
    token = Jwts.builder().setSubject(name).claim("roles", "user").setIssuedAt(new Date())
        .signWith(SignatureAlgorithm.HS256, "base64EncodedSecretKey").compact();
    return token;
  }
}

 測試token

現在就可以測試生成的token了,我們采用postman:

詳解前后端分離之Java后端

過濾器

這肯定是必須的呀,當然,也可以用AOP。

過濾要保護的url,同時在過濾器里進行token驗證

token驗證:

?
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
public class JwtFilter extends GenericFilterBean {
 
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String authHeader = request.getHeader("Authorization");
    if ("OPTIONS".equals(request.getMethod())) {
      response.setStatus(HttpServletResponse.SC_OK);
      chain.doFilter(req, res);
    } else {
      if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServletException("不合法的Authorization header");
      }
      // 取得token
      String token = authHeader.substring(7);
      try {
        Claims claims = Jwts.parser().setSigningKey("base64EncodedSecretKey").parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
      } catch (Exception e) {
        throw new ServletException("Invalid Token");
      }
      chain.doFilter(req, res);
    }
  }
 
}

要保護的url:/user下的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootApplication
public class AuthServerApplication {
 
  @Bean
  public FilterRegistrationBean jwtFilter() {
    FilterRegistrationBean rbean = new FilterRegistrationBean();
    rbean.setFilter(new JwtFilter());
    rbean.addUrlPatterns("/user/*");// 過濾user下的鏈接
    return rbean;
  }
 
  public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
  }
}

UserController

這個是必須經過過濾才可以訪問的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
@RequestMapping("/user")
public class UserController {
 
  @GetMapping("/success")
  public String success() {
    return "恭喜您登錄成功";
  }
 
  @GetMapping("/getEmail")
  public String getEmail() {
    return "xxxx@qq.com";
  }
}

關鍵測試

假設我們的Authorization錯了,肯定是通不過的:

詳解前后端分離之Java后端

當輸入剛才服務器返回的正確token:

詳解前后端分離之Java后端

允許跨域請求

現在來說前端和后端是兩個服務器了,所以需要允許跨域:

?
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
@Configuration
public class CorsConfig {
 
  @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTION");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("DELETE");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }
 
  @Bean
  public WebMvcConfigurer mvcConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "GET", "OPTIONS");
      }
    };
  }
}

下次是采用VueJS寫的前端如何請求。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/jimo_lonely/article/details/69357365

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩欧美在线观看一区二区三区 | 免费日韩 | 色官网| 中文在线一区二区 | 精品国产黄a∨片高清在线 久草.com | 亚洲一区 中文字幕 | 精品国产乱码久久久久久久软件 | 亚洲天堂高清 | 亚洲国产精品视频 | 日本中文字幕一区 | 亚洲美女久久 | 国产亚洲一区二区精品 | 欧美黄色网页 | 免费看黄的视频网站 | 欧美大片免费观看 | xxxx网 | 精品www| 欧美一级在线 | 欧美成人h版在线观看 | 亚洲国产精品成人 | 日韩一级免费观看 | 91免费观看视频 | 情一色一乱一欲一区二区 | 日本一区二区高清不卡 | 日韩精品www | 亚洲欧美另类图片 | 精品一区二区久久久久久久网站 | 日韩成人在线观看 | 久久久天堂国产精品 | 成人免费在线播放 | 日韩在线观看中文字幕 | 国产高清在线精品一区二区三区 | 国产亚洲精品久久久久久久久 | 91精品国产亚洲 | 欧美黄色一区二区 | 国产成人精品一区二区三区网站观看 | 五月天婷婷精品 | 久久久精品一区二区 | 午夜av一区二区 | 日韩三级电影 | 国产精品亚洲精品 |