Java, Spring boot, Swagger and form base authorization



我用BasicAuthenticationEntryPoint创建了rest-api。看起来像这样

@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
//response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName());
response.addHeader("WWW-Authenticate", "FormBased");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Marketplace");
super.afterPropertiesSet();
}
}

正如您已经注意到的,我正在使用"基于表单"的标头,以避免浏览器丑陋的授权窗口。前端 Angular 应用程序使用自己的授权表单。 它工作正常,但我也使用 Swagger 作为 rest-api 的自描述工具。对于 Swagger 和这样的标题 (response.addHeader("WWW-Authenticate", "FormBased");( 我有一个问题。Swagger 返回 401 错误,因为浏览器不建议授权窗口。 有没有办法使用带有标题的招摇 (response.addHeader("WWW-Authenticate", "FormBased");)而不是(response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName());(?

我已经找到了这个问题的解决方案。关键是我在WebSecurityConfigurerAdapter中配置了错误的安全配置。该配置保护了像这样的任何请求

http.csrf().disable().authorizeRequests()
.antMatchers("/api/registration/**").permitAll()
.antMatchers("/api/dictionary/**").permitAll()
.antMatchers("/api/common/**").permitAll()
.antMatchers("/api/advert_public/**").permitAll()
.antMatchers("/api/company_public/**").permitAll()
.anyRequest().hasRole(DEFAULT_ROLE)
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);

这样,Swagger入口点也需要登录名/密码。

现在我已经重写了配置以保护我的 api 中的特定方法,并且 Swagger 工作正常

http.csrf().disable().authorizeRequests()
.antMatchers("/api/advert/**").hasRole(DEFAULT_ROLE)
.antMatchers("/api/company/**").hasRole(DEFAULT_ROLE)
.antMatchers("/api/user/**").hasRole(DEFAULT_ROLE)
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);

如您所见,没有像.anyRequest().hasRole(DEFAULT_ROLE)这样的配置选项

最新更新