如何在swagger ui中显示spring security用户名密码验证筛选器url?

mec1mxoz  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(362)

我使用的是spring安全和用户名密码验证过滤器。我想知道是否可以在swagger中显示身份验证端点。这个端点是由过滤器自动生成的(据我所知)。
我真的想让这个端点出现在swaggerui中,否则我需要登录postman,然后使用带有jwt令牌的swagger,这有点奇怪。
这是usernamepasswordauthenticationfilter:

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;

public AuthenticationFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest req,
                                            HttpServletResponse res) {
    try {
        LoginDTO userEntity = new ObjectMapper().readValue(req.getInputStream(), LoginDTO.class);

        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(userEntity.getEmail(),
                        userEntity.getPassword(), new ArrayList<>())
        );
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                        Authentication auth) throws IOException {
    Token token = new Token(JwtUtils.createAccessToken(ZonedDateTime.now().plusMinutes(10), TenantContext.getCurrentUserUniqueIdentifier(), TenantContext.getCurrentTenantId()),
            JwtUtils.createRefreshToken(ZonedDateTime.now().plusMonths(3)));
    PrintWriter out = res.getWriter();
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");
    out.print(new ObjectMapper().writeValueAsString(token));
    out.flush();
}

}
这是我从websecurityadapter扩展而来的课程。如您所见,我将url设置为/v1/login。

@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final UserEntityDetailsService userEntityDetailsService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/v1/account").permitAll()
                .antMatchers(HttpMethod.GET, "/v1/healthcheck").permitAll()
                .antMatchers("/v1/recoverpassword/**").permitAll()
                .antMatchers("/swagger-ui/**", "/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(getAuthenticationFilter())
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

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

    public AuthenticationFilter getAuthenticationFilter() throws Exception {
        final AuthenticationFilter filter = new AuthenticationFilter(authenticationManager());
        filter.setFilterProcessesUrl("/v1/login");
        return filter;
    }
}

这是我的springfox配置:

@Configuration
@EnableSwagger2
public class SpringFoxConfig {

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Projeto List")
                .description("All endpoints of Projeto List Api")
                .build();
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("br.com.projetolist.resource"))
                .paths(PathSelectors.ant("/**"))
                .build()
                .securitySchemes(Arrays.asList(apiKey()));
    }

    /**
     * SwaggerUI information
     */
    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(1)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.MODEL)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .validatorUrl(null)
                .build();
    }

    private ApiKey apiKey() {
        return new ApiKey("jwtToken", "Authorization", "header");
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题