我正在使用springfox swagger2,并且运行正常。
这只是一个基本的设置/配置,因为我真的是招摇狂。
但是所有具有该URL的人都可以访问。
我希望每个人都不能访问它,并且拥有登录屏幕(基本身份验证或Google身份验证)确实很棒。
我一直在浏览互联网,但似乎找不到关于springfox-swagger2的特定内容。我可以找到一些,但似乎是针对.Net(基于C#的示例)。
更新
如果我在swagger-ui.html
类中设置了.antMatchers("/swagger-ui.html**").permitAll()
,则可以访问SecurityConfig
。
但是,如果我将其更改为.authenticated()
,它将不会,并且会收到我设置的401错误:
{"timestamp":"2018-09-03T06:06:37.882Z","errorCode":401,"errorMessagesList":[{"message":"Unauthorized access"}]}
似乎击中了我的身份验证入口点。如果我只能让所有经过身份验证的用户访问swagger-ui.html
(或整体上是昂首阔步)(目前,以后将基于角色)。
我不确定是否需要在SwaggerConfig.java
上添加一些安全性配置,因为我只需要使swagger-ui.html
对经过身份验证的用户(或特定角色/权限)可用。
依赖关系(pom.xml):
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
安全配置类
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
JWTAuthenticationFilter authenticationFilter =
new JWTAuthenticationFilter(authenticationManager(), appContext);
authenticationFilter.setFilterProcessesUrl("/auth/form");
JWTAuthorizationFilter authorizationFilter =
new JWTAuthorizationFilter(authenticationManager(), appContext);
http
.cors().and().csrf().disable() // no need CSRF since JWT based authentication
.authorizeRequests()
...
.antMatchers("/swagger-ui.html**").authenticated()
...
.anyRequest().authenticated()
.and()
.addFilter(authenticationFilter)
.addFilter(authorizationFilter)
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint());
}
...
}
MyAuthenticationEntryPoint
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final Logger logger = LoggerFactory.getLogger(MyAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) {
logger.debug("Pre-authenticated entry point called. Rejecting access");
List<Message> errorMessagesList = Arrays.asList(new Message("Unauthorized access"));
CommonErrorResponse commonErrorResponse =
new CommonErrorResponse(errorMessagesList, HttpServletResponse.SC_UNAUTHORIZED);
try {
String json = Util.objectToJsonString(commonErrorResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
httpServletResponse.getWriter().write(json);
} catch (Exception e1) {
logger.error("Unable to process json response: " + e1.getMessage());
}
}
}
Swagger配置
@EnableSwagger2
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(metadata())
.select()
.apis(RequestHandlerSelectors.basePackage("com.iyotbihagay.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo metadata() {
return new ApiInfoBuilder().title("Iyot Bihagay API Documentation")
.description("API documentation for Iyot Bihagay REST Services.").version("1.6.9").build();
}
}
我认为使用springfox是可能的,因为我可以在其他.net版本中看到它。
希望有人可以就如何保护Swagger UI(springfox-swagger2)达成共识。
顺便说一句,我正在为我的API使用JWT,它正在工作。
关于swagger,如果将其设置为permitAll()
,则可以正常工作。
如果将其更改为authenticated()
,它将不起作用。
如果它适用于authenticated()
,我将尝试应用角色/权限检查。
谢谢!
答案 0 :(得分:0)
为您的项目添加spring security,创建“ DEVELOPER_ROLE”,并以该角色创建用户,然后配置您的网络安全,将如下所示:
@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
//swagger-ui resources
private static final String[] DEVELOPER_WHITELIST = {"/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs"};
//site resources
private static final String[] AUTH_HTTP_WHITELIST = {"/path1", "/path2"}; // allowed
private static final String LOGIN_URL = "/login.html"; // define login page
private static final String DEFAULT_SUCCESS_URL = "/index.html"; // define landing page after successful login
private static final String FAILURE_URL = "/loginFail.html"; // define failed login page/path
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(AUTH_HTTP_WHITELIST).permitAll()
.antMatchers(DEVELOPER_WHITELIST).hasRole("DEVELOPER") // for role "DEVELOPER_ROLE"
.anyRequest()..authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL)
.defaultSuccessUrl(DEFAULT_SUCCESS_URL)
.failureUrl(FAILURE_URL)
.permitAll()
.and()
.logout()
.logoutSuccessUrl(LOGIN_URL)
.permitAll();
}
}
这里是示例教程: https://www.baeldung.com/spring-security-authentication-and-registration