我正在使用springfox swagger2,它正常工作。 这只是一个基本的设置/配置,因为我真的很新招摇。
但所有拥有网址的人都可以访问它。
我希望每个人都无法访问它,并且拥有一个登录屏幕(基本身份验证或谷歌身份验证)真的很棒。
我一直在寻找互联网,但似乎我找不到特定于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)。
顺便说一句,我正在使用JWT作为我的API,它正在运行。
关于招摇,如果我把它设置为permitAll()
它是有效的。
如果我把它改成authenticated()
它不起作用。
如果它适用于authenticated()
,我将尝试应用角色/权限检查。
谢谢!
为项目添加spring security,创建“DEVELOPER_ROLE”和具有该角色的用户,然后配置您的Web安全性,将如下所示:
@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