• 如何创建public class JwtAuthenticationWebFilter extends AuthenticationWebFilter


    关注 码龄 粉丝数 原力等级 -- 被采纳 被点赞 采纳率 zhminjian 2024-05-29 20:02 采纳率: 23.8% 浏览 1 首页/ 编程语言 / 如何创建public class JwtAuthenticationWebFilter extends AuthenticationWebFilter javaspring 如何创建public class JwtAuthenticationWebFilter extends AuthenticationWebFilter 收起 写回答 好问题 0 提建议 追加酬金 关注问题 微信扫一扫 点击复制链接 分享 邀请回答 编辑 收藏 删除 结题 收藏 举报 追加酬金 (90%的用户在追加酬金后获得了解决方案) 当前问题酬金 ¥ 0 (可追加 ¥500) ¥ 15¥ 20¥ 50¥ 100¥ 200 支付方式 扫码支付 二维码出错 点击刷新 支付金额 15 元 提供问题酬金的用户不参与问题酬金结算和分配 支付即为同意 《付费问题酬金结算规则》 结题 再想想 删除 再等等

    3条回答 默认 最新

    • 阿里嘎多学长 2024-05-29 20:03
      关注

      以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


      创建一个名为 JwtAuthenticationWebFilter 的类,它继承自 Spring Security 的 AuthenticationWebFilter 类,通常是为了在 Spring 应用中处理 JWT 认证。以下是创建和实现这个类的基本步骤,以及如何在 Spring 应用中使用它:

      步骤 1: 创建 JwtAuthenticationWebFilter 类

      首先,你需要创建一个继承自 AuthenticationWebFilter 的类。AuthenticationWebFilter 是 Spring Security 5.0 引入的,用于处理身份验证的 Web 过滤器。

      import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
      import org.springframework.security.core.context.SecurityContextHolder;
      import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
      import org.springframework.security.web.authentication.AuthenticationWebFilter;
      import org.springframework.security.core.Authentication;
      import org.springframework.security.core.AuthenticationException;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      
      public class JwtAuthenticationWebFilter extends AuthenticationWebFilter {
      
          private final JwtTokenProvider tokenProvider;
      
          public JwtAuthenticationWebFilter(AuthenticationManager authenticationManager, JwtTokenProvider tokenProvider) {
              super(authenticationManager);
              this.tokenProvider = tokenProvider;
          }
      
          @Override
          protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
                                                  Authentication authResult) throws IOException, ServletException {
              // 在认证成功后,可以在这里设置JWT令牌
              SecurityContextHolder.getContext().setAuthentication(authResult);
              response.addHeader("Authorization", "Bearer " + tokenProvider.generateToken(authResult));
          }
      
          @Override
          protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                    AuthenticationException failed) throws IOException, ServletException {
              // 在认证失败时,可以在这里处理错误
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          }
      
          @Override
          protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
              // 尝试从请求中解析JWT令牌,并进行认证
              JwtAuthenticationToken token = tokenProvider.parseToken(request);
              if (token == null) {
                  return null;
              }
              return getAuthenticationManager().authenticate(token);
          }
      }
      

      步骤 2: 创建 JwtTokenProvider 类

      JwtTokenProvider 类负责生成和解析 JWT 令牌。

      import io.jsonwebtoken.*;
      import org.springframework.security.core.Authentication;
      import org.springframework.stereotype.Component;
      import java.util.Date;
      
      @Component
      public class JwtTokenProvider {
      
          private final String secretKey = "your_secret_key";
      
          public String generateToken(Authentication authentication) {
              Date now = new Date();
              Date expiryDate = new Date(now.getTime() + 60 * 60 * 1000); // 1 hour validity
              return Jwts.builder()
                      .setSubject(authentication.getName())
                      .setIssuedAt(new Date())
                      .setExpiration(expiryDate)
                      .signWith(SignatureAlgorithm.HS512, secretKey)
                      .compact();
          }
      
          public JwtAuthenticationToken parseToken(HttpServletRequest request) {
              String authHeader = request.getHeader("Authorization");
              if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                  return null;
              }
              String token = authHeader.substring(7);
              try {
                  Jws claims = Jwts.parser()
                          .setSigningKey(secretKey)
                          .parseClaimsJws(token);
                  return new JwtAuthenticationToken(claims.getBody().getSubject());
              } catch (JwtException | IllegalArgumentException e) {
                  throw new RuntimeException("Invalid JWT token");
              }
          }
      }
      

      步骤 3: 配置 Spring Security

      你需要配置 Spring Security 以使用 JwtAuthenticationWebFilter

      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;
      
      @EnableWebSecurity
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http
                  .addFilterBefore(new JwtAuthenticationWebFilter(authenticationManager(), jwtTokenProvider()),
                                   UsernamePasswordAuthenticationFilter.class)
                  // 其他配置...
                  ;
          }
      
          @Bean
          public JwtTokenProvider jwtTokenProvider() {
              return new JwtTokenProvider();
          }
      }
      

      参考资料

      请注意,示例代码需要根据你的具体需求进行调整。例如,你需要替换 your_secret_key 为你的实际密钥,并根据你的应用需求调整 JWT 的有效期等。

      展开全部

      评论 编辑记录
    • 专家-赤兔[在线] 全栈领域优质创作者 2024-05-29 20:03
      关注

      引自免费微信小程序:皆我百晓生

      为了创建一个名为 JwtAuthenticationWebFilter 的类,它扩展了 Spring Security 的 AuthenticationWebFilter 类,你需要按照下面的步骤进行操作。

      首先确保你的项目已经添加了Spring Boot和Spring Security依赖。如果你正在使用Maven,可以在pom.xml文件中添加以下依赖:

      
          
              org.springframework.boot
              spring-boot-starter-security
          
      
      

      接下来,创建一个新的Java类,命名为 JwtAuthenticationWebFilter,并继承自 AuthenticationWebFilter。在类中,你需要覆盖一些方法以便处理JWT(JSON Web Tokens)的身份验证。这里是一个基本的示例:

      import org.springframework.security.core.Authentication;
      import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
      import org.springframework.util.Assert;
      import reactor.core.publisher.Mono;
      
      import javax.servlet.http.HttpServletRequest;
      import java.io.IOException;
      
      public class JwtAuthenticationWebFilter extends AuthenticationWebFilter {
      
          private final JwtTokenProvider jwtTokenProvider;
      
          public JwtAuthenticationWebFilter(JwtTokenProvider jwtTokenProvider) {
              super(new WebAuthenticationDetailsSource());
              this.jwtTokenProvider = Assert.notNull(jwtTokenProvider, "jwtTokenProvider cannot be null");
          }
      
          @Override
          protected Mono attemptAuthentication(HttpServletRequest request, FilterChain filterChain) throws IOException {
              String authToken = jwtTokenProvider.getTokenFromRequest(request);
              if (authToken != null && jwtTokenProvider.validateToken(authToken)) {
                  return Mono.just(jwtTokenProvider.getAuthentication(authToken));
              }
              return Mono.empty();
          }
      
          @Override
          protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                  FilterChain chain, Authentication authResult) throws IOException {
              // If you want to add custom logic on successful authentication, do it here.
              super.successfulAuthentication(request, response, chain, authResult);
          }
      }
      

      在这个例子中,我们假设有一个 JwtTokenProvider 类,它是用于解析、验证和从请求头中提取JWT的工具类。你需要根据实际需求实现这个类。这是一个简单的 JwtTokenProvider 示例:

      import io.jsonwebtoken.Claims;
      import io.jsonwebtoken.Jwts;
      import io.jsonwebtoken.SignatureAlgorithm;
      import org.springframework.stereotype.Component;
      
      import java.util.Date;
      import java.util.HashMap;
      import java.util.Map;
      
      @Component
      public class JwtTokenProvider {
      
          private static final String SECRET_KEY = "your_secret_key";
          private static final long EXPIRATION_TIME_IN_SECONDS = 86400; // 1 day in seconds
          private static final String JWT_HEADER_NAME = "Authorization";
      
          public String generateToken(String username) {
              Map claims = new HashMap<>();
              claims.put("username", username);
      
              Date now = new Date();
              Date expiration = new Date(now.getTime() + EXPIRATION_TIME_IN_SECONDS * 1000L);
      
              return Jwts.builder()
                      .setClaims(claims)
                      .setSubject(username)
                      .setIssuedAt(now)
                      .setExpiration(expiration)
                      .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                      .compact();
          }
      
          public String getTokenFromRequest(HttpServletRequest request) {
              String headerValue = request.getHeader(JWT_HEADER_NAME);
              if (headerValue != null && headerValue.startsWith("Bearer ")) {
                  return headerValue.substring(7); // Remove "Bearer " prefix
              }
              return null;
          }
      
          public boolean validateToken(String token) {
              try {
                  Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
                  return true;
              } catch (Exception e) {
                  return false;
              }
          }
      
          public Authentication getAuthentication(String token) {
              Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
      
              return new UsernamePasswordAuthenticationToken(claims.getString("username"), null, Collections.emptyList());
          }
      }
      

      注意:这里的SECRET_KEY是硬编码的,并且签名算法使用的是HS256,这在生产环境中并不安全。你应该考虑使用环境变量或密钥管理服务来存储秘钥,并可能使用更安全的签名算法。

      要将此过滤器应用到Spring Security配置中,你需要在主配置类中注册它:

      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
      import org.springframework.security.config.web.server.ServerHttpSecurity;
      import org.springframework.security.web.server.SecurityWebFilterChain;
      
      @Configuration
      @EnableWebFluxSecurity
      public class SecurityConfig {
      
          @Bean
          public JwtTokenProvider jwtTokenProvider() {
              return new JwtTokenProvider();
          }
      
          @Bean
          public JwtAuthenticationWebFilter jwtAuthenticationWebFilter(JwtTokenProvider jwtTokenProvider) {
              return new JwtAuthenticationWebFilter(jwtTokenProvider);
          }
      
          @Bean
          public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
              http
                  .authorizeExchange()
                      .anyExchange().authenticated()
                      .and()
                  .addFilterBefore(jwtAuthenticationWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
                  .csrf().disable(); // Depending on your application needs, consider enabling CSRF protection
      
              return http.build();
          }
      }
      

      这段代码告诉Spring Security使用你定义的 JwtAuthenticationWebFilter 进行身份验证。同时,你也应该为其他资源设置适当的访问控制规则。

      这就是创建一个基于JWT的身份验证Web过滤器的基本过程。根据你的具体需求,你可能需要对这些类进行修改和扩展。

      展开全部

      评论 编辑记录
    • 夜郎king 2022博客之星IT其它领域TOP 12 2024-06-04 08:48
      关注

      上面已经有博主给出了答案,直接使用即可。

      评论
    编辑
    预览

    报告相同问题?

  • 相关阅读:
    【生物信息学】奇异值分解(SVD)
    Java设计模式 | 七大原则之迪米特法则
    《德米安》从那以后伤口很痛,但偶尔我会找到钥匙,沉入心底
    (C语言)printf打印的字符串太长了,我想分两行!
    成为一名优秀的测试工程师必备条件
    494. 目标和
    【MyBatis】MyBatis日志信息配置
    C++官网 Tutorials C++ Language Basics of C++:Constants
    企业信息化建设过程中,如何走出困境?
    视频时序动作识别(video action recognition)介绍
  • 原文地址:https://ask.csdn.net/questions/8111313