来到JavaEE我爱编程程序员

Spring Boot + Spring Security +

2018-04-12  本文已影响808人  板凳儿儿

Spring Boot + Spring Security + JWT + Vue 权限控制

    使用spring boot+spring security+vue开发了一个demo,完善了权限管理的功能,接下来要介绍本项目使用的技术和架构思路,本项目不采用分离部署的方式。

1. JWT
2. Spring Security
3. Vue(前端自动化构建,自定义指令搭配Spring Security)
4. 分离开发模式
5. 项目打包(前后端分离开发,统一打成一个jar包)
6. 参考资料

一. JWT

    JWT即JSON Web Token(JWT)是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。

    本项目使用JWT来判断记录用户登陆信息,接口访问权限控制。结合Spring Security,自定义一个JWTFilter在,Spring Security的filter之前执行。

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
        String authHeader = request.getHeader(Constant.JWT_HEADER);
        if (authHeader != null && authHeader.startsWith(Constant.JWT_TOKEN_HEADER)) {
            final String authToken = authHeader.substring(Constant.JWT_TOKEN_HEADER.length()); 
                        // The part after "Bearer "
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            logger.info("checking authentication " + username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                                    request));
                    logger.info("authenticated user " + username + ", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
            else
            {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}

先校验用户header传过来的token,校验通过则把该用户放入spring此次回话中,并继续。否则返回401。此处filter继承OncePerRequestFilter,因为filter会被自动注入serverlet中,我们使用的时候又会注入到spring boot容器中,会导致filter执行两次,继承OncePerRequestFilter可以解决这个问题。

二. Spring Security

    Spring系列的安全框架,一种基于 Spring AOP 和 Servlet 过滤器的安全框架。它提供全面的安全性解决方案,同时在 Web 请求级和方法调用级处理身份确认和授权。

    和以往不同的是,本项目不采用session的形式,而是结合JWT。

Configurer

    @Override
    protected void configure(HttpSecurity http) {

        try
        {
            http
                // we don't need CSRF because our token is invulnerable
                .csrf().disable()
                // exceptionHandling
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // don't create session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/rest/**").authenticated()
                .antMatchers("/admin").hasAuthority("admin")
                .antMatchers("/ADMIN").hasRole("ADMIN")
                .anyRequest().permitAll();
            // Custom JWT based security filter
            http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
            // disable page caching
            http.headers().cacheControl();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }

    }

}

使用addFilterBefore将JWT过滤器加在spring过滤器之前,此配置spring会拦截所有rest请求,可以针对权限和角色单独设置拦截。也可以使用注解@PreAuthorize("hasRole('ROLE_ADMIN')")在类和方法的上。

三. Vue

此处主要介绍vue和jwt控制权限的思路。

  1. 前端路由控制
登陆成功后,会把后台返回的token放入cookie,路由中加入一个判断参数,给一个布尔值,
根绝布尔值拦截需要拦截的路由,检查是否携带token,如果有放行,如果没有则返回登录页
// 路由
{
    path:'/profile',
    name: 'profile',
    component: profile,
    meta: {
      requireAuth: true,
      wrapper: true
    }
  }
// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if ( localCookie.getLocalCookie("token") !== null ) {
      next();
    }
    else {
      next({
        path: '/',
        query: {redirect: to.fullPath}
      });
    }
  }
  else {
    next();
  }
});
  1. http访问请求
    本项目HTTP库使用axios,对axios做了一层封装。
发送请求之前拦截请求,取出cookie中的token放入header中,以便后台鉴权。返回的时候拦截response,如果有401报错信息,则证明token鉴权失败,
清除cookie,跳转至登陆页
// http request 拦截器
axios.interceptors.request.use(
  config => {
    const token = localCookie.getLocalCookie('token');
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/json; charset=utf-8',
      'Authorization':token
    };
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
        switch (error.response.status) {
            case 401:
              // 401 清除token信息并跳转到登录页面
              localCookie.delCookie('token');
              router.push('/');
        }
    }
    return Promise.reject(error.response);
  });
  1. 权限标签
    无论是之前的项目使用jsf,还是spring推荐的模板引擎thymleaf,都可以写jsp标签,来获取用户的权限以控制按钮等空间在前端页面的展示。vue中不建议这么做,此项目分离开发的模式更不能这么做,所以可以自己封装一个vue的指令去替代jsp标签。
import Vue from 'vue';
import * as restService from '../until/restService';
Vue.directive('permission', {
  bind: function (el, binding) {
    restService.getPermissionList('/rest/user/permissions', {})
      .then(response => {
        if(response == 'UNAUTHORIZED'){
          // TODO
        }else{
          NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
          let result = 0;
          for( let res of response.data ){
            for( let bind of binding.value ){
              if( res == bind ){
                result += 1;
              }
            }
          }
          if( result > 0 ){
            el.style.display="";
          }else{
            el.style.display="none";
          }
        }
      })
      .catch(error => {
        console.log(error);
        el.style.display="none";
      });
  }
});

使用方式:

只需要把该指令放到任意一个想要控制其权限的标签当中就可了
<router-link tag="li" to="/router" v-permission="['PERMISSION_USER']" active-class="active">
    <a><i class="fa fa-circle-o"></i>router</a>
</router-link>

四. 分离开发

此处分离开发指的是前后端分离开发,关注点分离。前端使用vue-cli(基于webpack)自动构建,
编译、打包,这样前端可以写vue的单文件组件及其他一些新特性,js方面也可以写更新的语法(es6以上)。前后端分离开发有一个问题就是前端程序访问后端接口的时候可能会有跨域的问题,这个可以在后端服务做设置,也可以在前端做代理配置。本项目选择后者,webpack配置文件中是区分开发和产品环境的,可以在开发环境配置HTTP访问代理,在产品环境中配置打包路径,这样所有问题就都解决了。

五. 项目打包

使用一个maven打包工具(exec-maven-plugin),可以执行命令行

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>exec-npm-install</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>${npm}</executable>
                        <arguments>
                            <argument>install</argument>
                        </arguments>
                        <workingDirectory>${basedir}/front</workingDirectory>
                    </configuration>
                </execution>

                <execution>
                    <id>exec-npm-run-build</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>${npm}</executable>
                        <arguments>
                            <argument>run</argument>
                            <argument>build</argument>
                        </arguments>
                        <workingDirectory>${basedir}/front</workingDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

执行mvn package,会在front目录中先执行npm install、npm run dev,这两条命令会把前端代码编译打包到spring boot的静态目录中(此前需要修改前端项目打包配置,配置好打包路径)。

六. 参考资料

spring projects: https://spring.io/docs/reference

vue: https://cn.vuejs.org/v2/guide/

vue-router: https://router.vuejs.org/zh-cn/index.html

项目使用ui:AdminLTE,element-ui,bootstrap-vue

想写一些东西分享,欢迎转载,请注明出处。
简书-板凳儿儿
https://www.jianshu.com/p/f47c7b6b3bf7
上一篇下一篇

猜你喜欢

热点阅读