前后端分离之Java后端

前后端分离的思想由来已久,不妨尝试一下,从上手开始,先把代码写出来再究细节。

代码下载:https://github.com/jimolonely/AuthServer

前言
以前服务端为什么能识别用户呢?对,是session,每个session都存在服务端,浏览器每次请求都带着sessionId(就是一个字符串),于是服务器根据这个sessionId就知道是哪个用户了。 
那么问题来了,用户很多时,服务器压力很大,如果采用分布式存储session,又可能会出现不同步问题,那么前后端分离就很好的解决了这个问题。

前后端分离思想: 
在用户第一次登录成功后,服务端返回一个token回来,这个token是根据userId进行加密的,密钥只有服务器知道,然后浏览器每次请求都把这个token放在Header里请求,这样服务器只需进行简单的解密就知道是哪个用户了。这样服务器就能专心处理业务,用户多了就加机器。当然,如果非要讨论安全性,那又有说不完的话题了。

下面通过SpringBoot框架搭建一个后台,进行token构建。

构建springboot项目
我的目录结构:(结果未按标准书写,仅作说明)

1

不管用什么IDE,最后我们只看pom.xml里的依赖: 
为了尽可能简单,就不连数据库了,登陆时用固定的。

devtools:用于修改代码后自动重启; 
jjwt:加密这么麻烦的事情可以用现成的,查看https://github.com/jwtk/jjwt

<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

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:

2

过滤器
这肯定是必须的呀,当然,也可以用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);
    }
}

关键测试
假设我们的Authorization错了,肯定是通不过的:

3

当输入刚才服务器返回的正确token:

4

允许跨域请求
现在来说前端和后端是两个服务器了,所以需要允许跨域:

@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写的前端如何请求。

猜你喜欢

转载自blog.csdn.net/caseywei/article/details/83446716