swagger页面直接添加token+网关验证

本文介绍了如何在Swagger中配置token,以便在Swagger页面上进行接口测试时添加授权。通过`securitySchemes`和`securityContexts`方法设置,使得所有接口请求头自动包含token。配置完成后,Swagger页面上的authoritation字段可以输入token,对于本地服务或有拦截器的环境,需确保使用正确token。
摘要由CSDN通过智能技术生成

swagger页面直接添加token

概述

最近项目看到swagger.config是像下面这样配置的,然后进去页面右上角有个authoritation,访问接口需要把token传进去。

package com.gsafety.homeCharge.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(true)
            .apiInfo(apiInfo())
            .useDefaultResponseMessages(false)
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .build()
            .securitySchemes(securitySchemes())
            .securityContexts(securityContexts());
  }


  private List<ApiKey> securitySchemes() {
    List<ApiKey> apiKeyList= new ArrayList<>();
    apiKeyList.add(new ApiKey("token", "token", "header"));
    return apiKeyList;
  }

  private List<SecurityContext> securityContexts() {
    List<SecurityContext> securityContexts=new ArrayList<>();
    securityContexts.add(
            SecurityContext.builder()
                    .securityReferences(defaultAuth())
                    .forPaths(PathSelectors.regex("^(?!auth).*$"))
                    .build());
    return securityContexts;
  }

  private List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    List<SecurityReference> securityReferences=new ArrayList<>();
    securityReferences.add(new SecurityReference("token", authorizationScopes));
    return securityReferences;
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("")//大标题
            .version("1.0")//版本
            .build();
  }

}
如何配置:

其实上述代码就可以完成了,关键就是private List securitySchemes()

​ 和private List defaultAuth()

两个方法,想要复用的可以直接ctrl+CV啥都不用改

配置完之后,进去swagger页面然后,填写完token之后,该swagger页面所有的接口的请求头里面都会加上token:“xxxxxxxx”。

加上之后
  • 假如你是本地服务启动的话,并且没写拦截器或者过滤器验证token的话,随便填写个token就行
  • 假如编写了拦截器或者过滤器,或者该请求要走网关的时候,就需要获取到正确的token才行。
为了在Swagger添加token,可以使用Spring Security来保护API并生成token。以下是如何在Spring Boot应用程序中使用SwaggerSpring Security整合token的步骤: 1. 添加Spring Security和JWT依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> ``` 2. 创建Spring Security配置类 创建一个类,继承WebSecurityConfigurerAdapter并重写configure(HttpSecurity http)方法。在该方法中,配置Spring Security以保护API并生成token。以下是一个示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } ``` 3. 创建JWT工具类 创建一个类,用于生成和解析JWT token。以下是一个示例: ``` @Component public class JwtUtils { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private int expiration; public String generateToken(Authentication authentication) { UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); Date now = new Date(); Date expiryDate = new Date(now.getTime() + expiration); return Jwts.builder() .setSubject(userPrincipal.getUsername()) .setIssuedAt(now) .setExpiration(expiryDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getUsernameFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject(); } public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secret).parseClaimsJws(authToken); return true; } catch (SignatureException ex) { log.error("Invalid JWT signature"); } catch (MalformedJwtException ex) { log.error("Invalid JWT token"); } catch (ExpiredJwtException ex) { log.error("Expired JWT token"); } catch (UnsupportedJwtException ex) { log.error("Unsupported JWT token"); } catch (IllegalArgumentException ex) { log.error("JWT claims string is empty"); } return false; } } ``` 4. 创建JWT认证过滤器 创建一个类,用于验证token并将用户信息添加Spring Security上下文中。以下是一个示例: ``` public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && jwtUtils.validateToken(jwt)) { String username = jwtUtils.getUsernameFromToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { log.error("Could not set user authentication in security context", ex); } filterChain.doFilter(request, response); } private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } } ``` 5. 在Swagger添加tokenSpring Boot应用程序中添加Swagger,并在Swagger配置类中添加以下代码: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired private JwtUtils jwtUtils; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .securityContexts(Arrays.asList(securityContext())) .securitySchemes(Arrays.asList(apiKey())) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiKey apiKey() { return new ApiKey("JWT", "Authorization", "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(Arrays.asList(new SecurityReference("JWT", new AuthorizationScope[]{}))) .forPaths(PathSelectors.any()) .build(); } @Bean public SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId(null) .clientSecret(null) .realm(null) .appName(null) .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .displayRequestDuration(true) .validatorUrl("") .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/"); } @Bean public SecurityConfiguration securityConfiguration() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public SecurityConfiguration securityConfiguration() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = new ArrayList<>(); authorizationScopeList.add(new AuthorizationScope("read", "read all")); authorizationScopeList.add(new AuthorizationScope("write", "access all")); List<GrantType> grantTypes = new ArrayList<>(); GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant("http://localhost:8080/auth/token"); grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2schema", authorizationScopeList, grantTypes); } @Bean public SecurityConfiguration securityInfo() { return new SecurityConfiguration( "test-app-client-id", "test-app-client-secret", "test-app-realm", "test-app", "", ApiKeyVehicle.HEADER, "Authorization", "," ); } @Bean public SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public UiConfiguration uiConfiguration() { return new UiConfiguration( null, "none", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L ); } } ``` 完成以上步骤后,您就可以在Swagger中使用token来访问受保护的API了。在Swagger界面的右上方,单击“Authorize”按钮并输入您的token即可。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值