我正在尝试通过Spring安全性来保护基于CXF的rest API。尽管我的配置在技术上可行,但我似乎无法使API响应401,而不是响应401上的HTML消息。基于其他一些SO帖子,我使用groovy将以下java配置整合到了Spring安全配置中:
@Configuration
@EnableWebSecurity
@Slf4j
class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) {
http.antMatcher('/api/**')
.authorizeRequests()
.antMatchers('/api/admin/**').hasRole('ADMIN')
.antMatchers('/api/**').hasRole('USER')
.and()
.httpBasic()
.and()
.addFilterBefore(
new BasicAuthenticationFilter(authenticationManager: authenticationManager(), authenticationEntryPoint: new BasicJsonEntryPoint(realmName: 'Local')),
BasicAuthenticationFilter.class
)
}
static class BasicJsonEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest req, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
log.debug 'Handling response'
response.addHeader HttpHeaders.WWW_AUTHENTICATE, /Basic realm="${getRealmName()}"/
response.setStatus HttpStatus.UNAUTHORIZED.value()
response.getWriter().println([status: HttpStatus.UNAUTHORIZED.value(), message: e.getMessage()].toJson())
}
}
}
我已经尝试了这种通用方法的多种变体,但是无论我从API获得HTML为何。请参阅以下要求/要求:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 401 Full authentication is required to access this resource</title>
</head>
<body>
<h2>HTTP ERROR 401</h2>
<p>Problem accessing /api/test. Reason:
<pre> Full authentication is required to access this resource</pre>
</p>
<hr />
<i>
<small>Powered by Jetty://</small>
</i>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</body>
</html>
我只是在猜测,但是有时当您的应用程序发出200s以外的http响应代码时,Jetty会有所帮助。我的建议是您在web.xml中添加一些逻辑以缩短Jetty的帮助。使我的应用程序摆脱类似问题的完整技术记录在:如何抑制Jetty 8的默认ErrorHandler?
祝好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句