Spring Security 如何让JWT身份验证在spring Boot 3上工作

2mbi3lxu  于 2023-02-16  发布在  Spring
关注(0)|答案(1)|浏览(203)

我一直在尝试在 Boot 上设置springsecurity以使用JWT,但到目前为止,它还没有工作。
每当我启动我的spring Boot API应用程序时,除了/actuator之外,我的端点都不会暴露,而且我一直得到一个默认密码。
下面是我的安全配置类:

@Configuration
@EnableMethodSecurity
@RequiredArgsConstructor
public class ApiSecurityConfig {
    private final AuthenticationTokenFilter authenticationTokenFilter;
private final UserDetailsServiceImpl userDetailsService;

private final CustomAuthenticationEntryPoint entryPoint;

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService);
    authenticationProvider.setPasswordEncoder(passwordEncoder());

    return authenticationProvider;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .exceptionHandling(e -> e.authenticationEntryPoint(entryPoint))
            .authorizeHttpRequests(authorizeRequests -> authorizeRequests
                    .requestMatchers("/merchant/auth/**").permitAll()
                    .requestMatchers("/swagger-ui.html").permitAll()
                    .anyRequest().authenticated())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    http.authenticationProvider(authenticationProvider());
    http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}
}

编辑:下面是我的身份验证令牌过滤器:

@Slf4j
@Configuration
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = "";
        String headerAuthorization = request.getHeader("Authorization");

        if (StringUtils.hasText(headerAuthorization) && headerAuthorization.startsWith("Bearer ")) {
            jwt = headerAuthorization.substring(7, headerAuthorization.length());
        }

        try {
            if (!jwt.isEmpty() && jwtUtils.validateJwt(jwt)) {
                String username = jwtUtils.getUsernameFromJwt(jwt);

                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.getWriter().write("{\"status\": \"false\", \"message\": \"Access denied\", \"data\": \"Invalid token\"}");
                response.getWriter().flush();
                return;
            }
        } catch (InvalidKeySpecException e) {
            log.error("Invalid key spec exception thrown:", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("No such algorithm exception thrown:", e);
        }
    }
}
7qhs6swi

7qhs6swi1#

多亏了Tangrunze,我才发现我错过了filterChain.doFilter(请求,响应);
但是同样,我发现我的主类中有一个componentScan注解,因为我试图在不同的maven项目中拾取一些组件。
显然,如果您在配置所在的驻留包之前扫描其他基础包,那么springsecurityauto配置就会启动。

相关问题