源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

详解前后端分离之Java后端

  • 时间:2021-12-30 10:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:详解前后端分离之Java后端
前后端分离的思想由来已久,不妨尝试一下,从上手开始,先把代码写出来再究细节。 代码下载:[url=https://github.com/jimolonely/AuthServer]https://github.com/jimolonely/AuthServer[/url] [b]前言[/b] 以前服务端为什么能识别用户呢?对,是session,每个session都存在服务端,浏览器每次请求都带着sessionId(就是一个字符串),于是服务器根据这个sessionId就知道是哪个用户了。 那么问题来了,用户很多时,服务器压力很大,如果采用分布式存储session,又可能会出现不同步问题,那么前后端分离就很好的解决了这个问题。 前后端分离思想: 在用户第一次登录成功后,服务端返回一个token回来,这个token是根据userId进行加密的,密钥只有服务器知道,然后浏览器每次请求都把这个token放在Header里请求,这样服务器只需进行简单的解密就知道是哪个用户了。这样服务器就能专心处理业务,用户多了就加机器。当然,如果非要讨论安全性,那又有说不完的话题了。 下面通过SpringBoot框架搭建一个后台,进行token构建。 [b]构建springboot项目[/b] 我的目录结构:(结果未按标准书写,仅作说明) [img]http://files.jb51.net/file_images/article/201705/2017052410395617.png[/img] 不管用什么IDE,最后我们只看pom.xml里的依赖: 为了尽可能简单,就不连数据库了,登陆时用固定的。 devtools:用于修改代码后自动重启; jjwt:加密这么麻烦的事情可以用现成的,查看[url=https://github.com/jwtk/jjwt]https://github.com/jwtk/jjwt[/url]
<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>

[b]登录[/b] 这里的加密密钥是:base64EncodedSecretKey
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;
  }
}

[b] 测试token[/b] 现在就可以测试生成的token了,我们采用postman: [img]http://files.jb51.net/file_images/article/201705/2017052410395618.png[/img] [b]过滤器[/b] 这肯定是必须的呀,当然,也可以用AOP。 过滤要保护的url,同时在过滤器里进行token验证 token验证:
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下的:
@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);
  }
}

[b]UserController[/b] 这个是必须经过过滤才可以访问的:
@RestController
@RequestMapping("/user")
public class UserController {

  @GetMapping("/success")
  public String success() {
    return "恭喜您登录成功";
  }

  @GetMapping("/getEmail")
  public String getEmail() {
    return "xxxx@qq.com";
  }
}

[b]关键测试[/b] 假设我们的Authorization错了,肯定是通不过的: [img]http://files.jb51.net/file_images/article/201705/2017052410395619.png[/img] 当输入刚才服务器返回的正确token: [img]http://files.jb51.net/file_images/article/201705/2017052410395620.png[/img] [b]允许跨域请求[/b] 现在来说前端和后端是两个服务器了,所以需要允许跨域:
@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写的前端如何请求。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部