2
我想安全基於CXF的休息API與春季安全。儘管我的配置在技術上有效,但我似乎無法使用JSON響應JSON而不是HTML消息。基於其他一些SO帖子,我使用groovy爲彈簧安全配置組織了以下java配置:春季安全http基本auth與Java配置休息api
@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的方式。請參閱下面的請求/ RESP:
<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>
這似乎不能解決問題。我嘗試過使用Jetty,Tomcat和Undertow。相同的結果。 – Todd