Code Monkey home page Code Monkey logo

springsecurity-jwt-vue-deom's Introduction

JWT Spring Boot Security

Chinese Documents 中文文档

About

This is a demonstration of stateless token-based authentication using JSON Web Token and CSRF protection, Spring Security, Spring Boot and Vue js.

Technology Stack

Component Technology
Frontend Vue.js 2
Backend (REST) SpringBoot (Java)
Security Token Based (Spring Security, JJWT, CSRF)
Client Build Tools vue-cli, Webpack, npm
Server Build Tools Maven

Quick start

Run Environment: Java11, Node 12, Maven3

Clone this project

git clone https://github.com/PuZhiweizuishuai/SpringSecurity-JWT-Vue-Deom.git

Run back end server

cd spring-security-jwt
mvn clean package

Then

java -jar target/security-0.0.1-SNAPSHOT.jar

Run front end server

cd vue
npm install

Then

npm run serve

Final

Open

http://127.0.0.1:8080

Screenshots

主页

登陆

管理员页

Security

JWT token

To generating and verifying JWT I use JJWT. JJWT – a self-contained Java library providing end-to-end JSON Web Tokens creation and verification.

JWT storing strategy

We have a couple of options where to store the token:

HTML5 Web Storage (localStorage or sessionStorage) Cookies

Main problem of Web Storage

It is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks.

So, to prevent XSS I store the JWT token in a Http-Only/Secure cookie. Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS.

CSRF attack

However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF). A CSRF attack is a type of attack that occurs when a malicious web site, email, or blog causes a user’s web browser to perform an unwanted action on a trusted site on which the user is currently authenticated.

To prevent CSRF attacks, we must create an extra Javascript readable cookie which is called: XSRF-TOKEN. This cookie must be created when the user is logged in and should contain a random, un-guessable string. Every time the JavaScript application wants to make a request, it will need to read this token and send it along in a custom HTTP header.

Reference document

Spring Security Reference

Vue.js

Dependency software

mavonEditor

element ui

Copyright and license

The code is released under the MIT license.

springsecurity-jwt-vue-deom's People

Contributors

puzhiweizuishuai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

springsecurity-jwt-vue-deom's Issues

请教:Spring Security + JWT +Vue + History Mode浏览器刷新问题

大神,
如果前端Vue-Router采用History Mode,当刷新浏览器时,URL总是会跳转到登录页面,请问在后端该如何处理?附上部分代码,请帮我看下,不甚感激。

public class SecurityConfig extends WebSecurityConfigurerAdapter{
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
      .anyRequest().authenticated();
    http.formLogin().loginPage("/login");
    http.addFilter(new JWTAuthenticationFilter(authenticationManager())) // 用户名,密码验证,验证成功会返回token给客户端
      .addFilter(new JWTAuthorizationFilter(authenticationManager()))
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }
}

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
  public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
    super(authenticationManager);
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = request.getHeader(Constant.REQUEST_HEADER_AUTH);
    // 问题出在这里,当(正常情况)调用rest api时,前端会把token带上,请求是合法的
    // 但是当刷新浏览器时,此时header = null,请求不合法,然后就会跳转到/login页面
    if (header == null || !header.startsWith(Constant.TOKEN_PREFIX)) {
      chain.doFilter(request, response);
      return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(request, response);
  }

  private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    if (token != null) {
      // parse the token.
      String user = Jwts.parser().setSigningKey("secret").parseClaimsJws(token.replace("Bearer ", "")).getBody().getSubject();
      if (user != null) {
        return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
      }
      return null;
    }
    return null;
  }

请教有关使用Vuex store的细节

作者您好,在看你的代码的时候发现你的前端把服务器传回的数据放在了localStorage和store里。我觉得只存在localStorage就可以了吧?不知道Vuex的store存一份数据是有什么别的用途?谢谢大神!

HttpOnly

大佬你好,我想问下,cookie设置了httpOnly,前端不可读取cookie里的数据了,那用户注销的问题解决怎么?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.