简体   繁体   English

如何在spring security中添加所有请求的jwt认证标头?

[英]How to add jwt authendication header with all requests in spring security?

I followed this link and set up the jwt authentication. 我按照这个链接设置了jwt身份验证。 It is working fine. 它工作正常。 All requests are made from java script by attaching the authentication header like below in that. 所有请求都是通过附加如下所示的身份验证标头从java脚本生成的。

    $.ajax({
        url: "/user",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        headers: "Authorization": token,
        success: function (data, textStatus, jqXHR) {
            var $userInfoBody = $userInfo.find("#userInfoBody");

            $userInfoBody.append($("<div>").text("Username: " + data.username));
            $userInfoBody.append($("<div>").text("Email: " + data.email));

            var $authorityList = $("<ul>");
            data.authorities.forEach(function (authorityItem) {
                $authorityList.append($("<li>").text(authorityItem.authority));
            });
            var $authorities = $("<div>").text("Authorities:");
            $authorities.append($authorityList);
            $userInfoBody.append($authorities);
            $userInfo.show();
        }
    });

But I want this to be attached to all the subsequent requests not via javascript. 但我希望这不是通过javascript附加到所有后续请求。

Here is my security Config 这是我的安全配置

httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
            // don't create session
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            // allow anonymous resource requests
            .antMatchers(HttpMethod.GET, "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js")
            .permitAll().antMatchers("/auth/**").permitAll().antMatchers("/vendors/**").permitAll()
            .antMatchers("/production/images/**").permitAll().anyRequest().authenticated().and().formLogin()
            .loginPage("/login").loginProcessingUrl("/loginprocess").failureUrl("/?loginFailure=true").permitAll();

Here is my authentication filter 这是我的身份验证过滤器

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);
    System.out.println("Token is " + authToken);
    System.out.println("Username is " + username);
    System.out.println("Audience is from " + jwtTokenUtil.getAudienceFromToken(authToken));
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        System.out.println(userDetails.getAuthorities());
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            System.out.println("Token is invalid ");
        }
    }
    chain.doFilter(request, response);
}

How can I attach the authentication header to the response from the server after authentication. 如何在身份验证后将身份验证标头附加到服务器的响应中。 So that all the subsequent requests will automatically go with that authentication header. 这样所有后续请求都将自动与该认证头一起使用。

Is the approach I am thinking is correct? 我认为的方法是否正确? Or any other best approach is there? 还是有其他最好的方法吗?

The front end is responsible for adding the header to every request, not the back end. 前端负责为每个请求添加标头,而不是后端。 If you don't want to do this using JS, you can use a secure, httponly cookie. 如果您不想使用JS执行此操作,则可以使用安全的httponly cookie。 When you set a cookie form the backend, it will include it on every subsequent request to the domain it was issued from. 当您从后端设置cookie时,它将在每个后续请求中包含它到它发出的域。

However, there are some security concerns with using a cookie. 但是,使用cookie存在一些安全问题。 This article does a good job of explaining the security considerations. 本文很好地解释了安全性考虑因素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM