当前位置: 首页 > 知识库问答 >
问题:

Swagger UI被Spring Security阻止

闾丘博超
2023-03-14

我正在尝试使用JWT令牌实现Spring Security,我正在尝试使用方法级授权实现身份验证

我的配置类似于SwaggerConfig.java

@Configuration
@PropertySource({"classpath:application.properties"})
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfiguration implements WebMvcConfigurer {

    @Autowired
    private Environment env;

    @Value("${swagger.enable:false}")
    private Boolean isEnabled;

    @Bean
    public Docket swaggerBean() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(isEnabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.my.packageapi.v1"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(getApiInfo())
                .tags(new Tag(env.getProperty("swagger.display.project.name"), env.getProperty("swagger.display.project.description")));
    }

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title(env.getProperty("swagger.display.page.title"))
                .description(env.getProperty("swagger.display.module.description"))
                .version(env.getProperty("swagger.display.version"))
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/media/**", "/assets/**", "/static/**", "/images/**", "/css/**", "/js/**")
          .addResourceLocations("classpath:/assets/", "classpath:/static/media/", "classpath:/static/images/",
            "classpath:/static/css/", "classpath:/static/js/", "classpath:js/");
        registry.addResourceHandler("/dist/**").addResourceLocations("/dist/");
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
        //registry.addResourceHandler(contextPath+"/dist/**").addResourceLocations(contextPath+"/dist/");
        //registry.addResourceHandler(contextPath+"/static/**").addResourceLocations(contextPath+"/static/");
    }

}

Web安全配置.java

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Qualifier("userService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Qualifier("ApplicationAuthenticationManager")
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtAuthenticationFilter authenticationFilter;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public AuthenticationManager authenticationManagerBean() {
        return authenticationManager;
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/swagger**");

        http.cors().and().csrf().disable().
            authorizeRequests()
            .antMatchers(
                "/token/**",
                "/configuration/ui",
                "/swagger-resources/*",
                "/configuration/security",
                "/webjars/*",
                "/swagger-ui*",
                "/favicon*").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
            "/configuration/ui",
            "/swagger-resources/*",
            "/configuration/security",
            "/swagger-ui*",
            "/swagger-ui.html/*",
            "/webjars/*");
    }

JWT加密过滤器.java

    @Configuration
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Qualifier("userService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenProvider jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String header = req.getHeader(HEADER_STRING);
        String username = null;
        String authToken = null;
        if (header != null && header.startsWith(TOKEN_PREFIX)) {
            authToken = header.replace(TOKEN_PREFIX, "");
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
            } catch (IllegalArgumentException e) {
                logger.error("an error occurred during getting username from token", e);
            } catch (ExpiredJwtException e) {
                logger.warn("the token is expired and not valid anymore", e);
            } catch (SignatureException e) {
                logger.error("Authentication Failed. Username or Password not valid.");
            }
        } else {
            logger.warn("couldn't find bearer string, will ignore the header");
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = jwtTokenUtil.getAuthentication(authToken, SecurityContextHolder.getContext().getAuthentication(), userDetails);
                //UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
                logger.info("authenticated user " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        System.err.println("Filtering " + req.getContextPath() + "  " + req.getRequestURL());
        chain.doFilter(req, res);
    }
}

JWTAthenticationEntryPoint.java

    @Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }

我已经从这里开始跟踪了

已经尝试了许多解决方案,下面列出几个

昂首阔步UI空给403

如果您发现任何其他改进,请随时发表评论。每一点帮助都是值得赞赏的。

共有1个答案

郎正初
2023-03-14

在蚂蚁匹配器部分添加. antMatcher("/v2/api-docs","/配置/**", "/swagger*/**", "/webjars/**"). permitAll()

 类似资料:
  • SwaggerUI 汉化版;修改了部分样式;结合SpringFox SpringFox-Swagger-UI实现API管理

  • 我正在使用spring-boot 2.3.9和spring-security以及keycloak 12.0.4。 和我的服务bean创建配置 编辑:这可能与Spring-Cloud-Starter-Sleuth有关。如果我移除这个依赖关系,所有的事情就会像预期的那样工作。但我也需要侦探。

  • 我有一个小的vertx应用程序。一个超文本传输协议垂直获取一个请求,并通过带有请求-响应模式的eventbus发送它。所以类似于: 在DB Vertical中,我使用消费者获取一条消息,发送到DB,进行一些更改并发送回HTTP verticle。我的问题是,我有一个必须进行大量检查的删除操作,所以这个过程可能需要10秒钟。此时HTTP verticle仍然可以获得一些新请求,但DB consume

  • 问题内容: 因此,我有了这个Go http处理程序,该处理程序将一些POST内容存储到数据存储中,并检索其他一些信息作为响应。在后端,我使用: 在我的firefox OS应用程序中,我使用: 传入的部分都一直如此。但是,我的回复被阻止了。给我以下信息: 我尝试了许多其他操作,但是无法从服务器获得响应。但是,当我将Go POST方法更改为GET并通过浏览器访问该页面时,我得到的数据太糟糕了。我无法真

  • java.util.concurrent.CompletionException:Akka.Pattern.AskTimeoutException:收件人[Actor[akka:/web_server/user/MyActor#-769383443]]已终止。发送者[null]发送了类型为“com.data.model.request”的消息。 所以我重写了方法,在那里添加了一个log语句。 现在