Angular 7 + Spring Boot + h2数据库:JWT授权失败
创始人
2024-10-16 13:30:28
0

问题描述:

我正在使用Angular 7与Spring Boot开发一个项目,并使用h2数据库。我尝试使用JWT进行授权,但是无论如何都无法成功。

解决方法:

  1. 确保你的Angular应用已经正确地配置了JWT授权。你需要在每个HTTP请求的头部添加一个Authorization头,值为"Bearer {token}",其中{token}是你从后端接收到的JWT令牌。你可以使用Angular的HttpInterceptor来自动添加这个头部。

下面是一个示例的HttpInterceptor代码:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    const token = localStorage.getItem('jwtToken'); // 从localStorage中获取JWT令牌
    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}` // 添加Authorization头部
        }
      });
    }
    return next.handle(request);
  }
}

然后,在你的app.module.ts文件中将这个Interceptor添加到providers数组中:

import { JwtInterceptor } from './jwt.interceptor';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    // ...
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true } // 添加JwtInterceptor到providers数组中
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 确保你的后端Spring Boot应用正确地验证JWT令牌。你可以使用Spring Security来实现JWT授权。

首先,你需要创建一个自定义的UserDetailsService来获取用户信息。下面是一个示例代码:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException(username);
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
  }
}

然后,你需要创建一个自定义的JwtRequestFilter来验证JWT令牌。下面是一个示例代码:

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

  @Autowired
  private UserDetailsServiceImpl userDetailsService;

  @Autowired
  private JwtUtil jwtUtil;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    final String authorizationHeader = request.getHeader("Authorization");
    String username = null;
    String jwt = null;

    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
      jwt = authorizationHeader.substring(7);
      username = jwtUtil.extractUsername(jwt);
    }

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
      if (jwtUtil.validateToken(jwt, userDetails)) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
            userDetails, null, userDetails.getAuthorities());
        usernamePasswordAuthenticationToken
            .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
      }
    }

    chain.doFilter(request, response);
  }
}

最后,在你的SecurityConfig类中配置JWT授权。下面是一个示例代码:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private UserDetailsServiceImpl userDetailsService;

  @Autowired
  private JwtRequestFilter jwtRequestFilter;

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

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests().antMatchers("/authenticate").permitAll()
        .anyRequest().authenticated()
        .and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
  }
}

以上就是使用Angular 7 + Spring Boot + h2数据库进行JWT授权的解决方法。希望对你有帮助!

相关内容

热门资讯

玩家必看科普!wepoker作... 您好,pokemmo脚本最新版这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...
我来教大家!哈糖大菠萝软件下载... 1、我来教大家!哈糖大菠萝软件下载,aapoker插件,可靠教程(有挂方法);详细教程。2、哈糖大菠...
我来教教你!哈糖大菠萝万能挂,... 我来教教你!哈糖大菠萝万能挂,聚星ai辅助工具收费多少,实用技巧(有挂透明)关于聚星ai辅助工具收费...
玩家攻略推荐!wepoker有... 玩家攻略推荐!wepoker有辅助吗,德普之星透视辅助软件,2025版教程(有挂攻略);1.德普之星...
发现一款!werplan有挂吗... 发现一款!werplan有挂吗,wejoker私人辅助软件,必胜教程(有挂技巧);1.wejoker...
一分钟秒懂!wepoker安装... 一分钟秒懂!wepoker安装教程,来玩app 德州 辅助,教你攻略(有挂攻略)是由北京得来玩app...
玩家必看科普!智星德州可以透视... 玩家必看科普!智星德州可以透视吗,sohoo辅助,教你教程(有挂教程);人气非常高,ai更新快且高清...
玩家实测!wepoker轻量版... 玩家实测!wepoker轻量版有透视吗,来玩app破解版,wpk教程(有挂攻略);支持多人共享记分板...
分享个大家!wepoker有辅... 分享个大家!wepoker有辅助吗,德普辅助软件,安装教程(有挂方法);原来确实真的有挂(需添加指定...
一分钟秒懂!wepoker辅助... 一分钟秒懂!wepoker辅助器有哪些功能,wepoker免费脚本咨询,玩家教你(有挂攻略)准备好在...