How is it possible to return a json instead a html?
I got:
<!doctype html>
<html lang="en">
<head>
<title>HTTP Status 401 – Unauthorized</title>
<style type="text/css">
body {
font-family: Tahoma, Arial, sans-serif;
}
h1,
h2,
h3,
b {
color: white;
background-color: #525D76;
}
h1 {
font-size: 22px;
}
h2 {
font-size: 16px;
}
h3 {
font-size: 14px;
}
p {
font-size: 12px;
}
a {
color: black;
}
.line {
height: 1px;
background-color: #525D76;
border: none;
}
</style>
</head>
<body>
<h1>HTTP Status 401 – Unauthorized</h1>
</body>
</html>
i need something like this:
{
"errors": [
{
"status": "401",
"title": "UNAUTHORIZED",
"detail": "xyz ..."
}
]
}
My Adapter:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
// @formatter:off
httpSecurity
.csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET).permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(new CustomAuthenticationEntryPoint());
// @formatter:on
}
}
The CustomAuthenticationEntryPoint
@Component
class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint
{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException
{
Collection<String> authorities = response.getHeaders("Authorization");
response.addHeader("access_denied_reason", "authentication_required");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
}
}