提问者:小点点

用JWT和基本身份验证保护REST应用程序有意义吗?


我有一个Spring REST应用程序,它最初是用基本认证来保护的。

然后我添加了一个登录控制器,它创建了一个JWTJSON Web Token,用于后续请求。

我可以将以下代码移出登录控制器并进入安全过滤器吗?这样我就不再需要登录控制器了。

tokenAuthenticationService.addTokenToResponseHeader(responseHeaders, credentialsResource.getEmail());

或者我可以删除基本身份验证吗?

将基本身份验证与JWT混合使用是一个好的设计吗?

尽管一切都很好,但我还是有点不知道如何最好地设计这种安全性。


共2个答案

匿名用户

假设所有通信都有100%的TLS——在登录期间和登录后的所有时间——通过基本身份验证使用用户名/密码进行身份验证并接收JWT作为交换是一个有效的用例。这几乎正是OAuth 2流程之一(“密码授予”)的工作原理。

这个想法是最终用户通过一个endpoint进行身份验证,例如 /login/token 使用您想要的任何机制,并且响应应包含将在所有后续请求中发回的 JWT。JWT 应该是具有正确 JWT 过期 (exp) 字段的 JWS(即加密签名的 JWT):这可确保客户端无法操纵 JWT 或使其生存时间超过应有的时间。

您也不需要X-Auth-Token标头:HTTP身份验证承载方案是为这个确切的用例创建的:基本上,跟踪承载方案名称的任何信息位都是应该验证的“承载”信息。您只需设置授权标头:

Authorization: Bearer <JWT value here>

但是,也就是说,如果您的REST客户端是“不可信的”(例如,支持JavaScript的浏览器),我甚至不会这样做:HTTP响应中可通过JavaScript访问的任何值——基本上是任何头值或响应体值——都可能通过MITM XSS攻击被嗅探和拦截。

最好将JWT值存储在仅安全、仅http的cookie中(cookie config: setSecure(true),setHttpOnly(true))。这保证了浏览器将:

  1. 仅通过 TLS 连接传输 cookie,并且,
  2. 永远不要让 cookie 值可用于 JavaScript 代码。

这种方法几乎是实现最佳实践安全性所需的一切。最后一件事是确保您对每个HTTP请求都有CSRF保护,以确保向您的站点发起请求的外部域无法运行。

最简单的方法是设置一个具有随机值的仅安全(但不是仅http)cookie,例如UUID。

然后,在每次向服务器发送请求时,确保您自己的JavaScript代码读取cookie值并将其设置在自定义头中,例如X-CSRF-Token,并在服务器中的每个请求中验证该值。除非外部客户端通过HTTP选项请求获得授权,否则外部域客户端无法为发送到您的域的请求设置自定义标头,因此任何CSRF攻击尝试(例如,在IFrame中)都将失败。

这是我们所知的当今Web上不受信任的JavaScript客户端可用的最佳安全性。如果你好奇的话,斯托帕特也写了一篇关于这些技术的文章。HTH!

匿名用户

以下是一些代码来备份有关如何在Spring中执行此操作的公认答案……只需扩展UsernamePasswordAuth

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {

        this.authenticationManager = authenticationManager;

    }

    @Override

    public Authentication attemptAuthentication(HttpServletRequest req,

                                                HttpServletResponse res) throws AuthenticationException {

        try {

            ApplicationUser creds = new ObjectMapper()

                    .readValue(req.getInputStream(), ApplicationUser.class);

            return authenticationManager.authenticate(

                    new UsernamePasswordAuthenticationToken(

                            creds.getUsername(),

                            creds.getPassword(),

                            new ArrayList<>())

            );

        } catch (IOException e) {

            throw new RuntimeException(e);

        }

    }

    @Override

    protected void successfulAuthentication(HttpServletRequest req,

                                            HttpServletResponse res,

                                            FilterChain chain,

                                            Authentication auth) throws IOException, ServletException {

        String token = Jwts.builder()

                .setSubject(((User) auth.getPrincipal()).getUsername())

                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))

                .signWith(SignatureAlgorithm.HS512, SECRET)

                .compact();

        res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);

    }

}

使用JWT库。:

<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

Spring Boot配置类

package com.vanitysoft.payit.security.web.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

    import com.vanitysoft.payit.util.SecurityConstants;

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
         @Autowired
           private UserDetailsService userDetailsService;

            @Autowired
            private  BCryptPasswordEncoder bCryptPasswordEncoder;

         @Override
           protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(userDetailsService)
                      .passwordEncoder(bCryptPasswordEncoder);
           }

         @Override
            protected void configure(HttpSecurity http) throws Exception {
             http.cors().and().csrf().disable()
                    .authorizeRequests()                             
                        .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll()
                        .antMatchers("/user/**").authenticated()
                        .and()
                        .httpBasic()
                        .and()
                        .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                        .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and()
                        .logout()
                        .permitAll();

            }
    }