Spring security basic authentication configuration - spring

I've been trying to follow this tutorial :
https://www.baeldung.com/spring-security-basic-authentication
I have created a couple of rest endpoints like this :
#RestController
public class PostController {
#Autowired
PostCommentService postCommentService;
#Autowired
PostService postService;
#GetMapping("/comment")
public PostComment getComment(#RequestParam Long id) {
return postCommentService.findPostCommentById(id);
}
#PostMapping("/createPost")
public void createPost(#RequestBody PostDTO body){
postService.createPost(body);
}
}
Now for security I am using spring like this:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
This is the config class for spring security:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( "/comment").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
BasicAuthenticationFilter.class);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("password"))
.authorities("ROLE_USER");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
The CustomFilter looks like this:
public class CustomFilter extends GenericFilterBean {
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}
And this is the AuthenticationEntryPoint:
#Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException {
response.addHeader("WWW-Authenticate", "Basic realm= + getRealmName() + ");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
#Override
public void afterPropertiesSet(){
setRealmName("spring");
super.afterPropertiesSet();
}
}
Now the problem is that whenever I try to send a POST request I end up getting this error message:
HTTP Status 401 - Full authentication is required to access this resource
I have tried two approaches to send the request, one via postman
And the second one via curl:
curl -i --user admin:password --request POST --data {"text":"this is a new Post"} http://localhost:8080/createPost
I am at my wits' end here, hence the need to create this post. Any help will be much appreciated.
This is the curl response in case it might shed light on the matter:
1.1 401
Set-Cookie: JSESSIONID=6FE84B06E90BE7F2348C0935FE3DA971; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
WWW-Authenticate: Basic realm= + getRealmName() +
Content-Length: 75
Date: Thu, 10 Sep 2020 13:47:14 GMT
HTTP Status 401 - Full authentication is required to access this resource

This happens because Spring Security comes with CSRF protection enabled by default (and for a good reason). You can read about Cross Site Request Forgery here. In your case the CsrfFilter detects missing or invalid CSRF token and you're getting the 401 response. The easiest way to make your example work would be to disable csrf-ing in your security configuration but, of course, you shouldn't do this in a real application.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers( "/comment").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
BasicAuthenticationFilter.class);
}

Related

Spring Custom Authentication Provider- how to return custom REST Http Status when authentication fails

I have custom authentication provider that works fine:
#Component
public class ApiAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (isAuthorizedDevice(name, password)) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ApiInfo.Role.User));
final UserDetails principal = new User(name, password, grantedAuths);
return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
} else {
return null;
}
}
But it always return 401. I would like to change it in some cases to 429 for brute force mechanism. Instead of returning null I would like to return error: f.e.: 429. I think It should not be done here. It should be done in configuration: WebSecurityConfig but I have no clue how to achieve this.
I tried already throwing exceptions like:
throw new LockedException("InvalidCredentialsFilter");
throw new AuthenticationCredentialsNotFoundException("Invalid Credentials!");
or injecting respone object and setting there status:
response.setStatus(429);
But non of it worked. It always return 401.
F.e.:
curl http://localhost:8080/api/v1.0/time --header "Authorization: Basic poaueiccrmpoawklerpo0i"
{"timestamp":"2022-08-12T20:58:42.236+00:00","status":401,"error":"Unauthorized","path":"/api/v1.0/time"}%
And body:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Aug 12 22:58:17 CEST 2022
There was an unexpected error (type=Unauthorized, status=401).
Also could not find any docs or Baeldung tutorial for that.
Can You help me?
P.S My WebSecurityConfig:
#Configuration
#EnableWebSecurity
class WebSecurityConfig {
AuthenticationProvider apiAuthenticationProvider;
#Bean
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().and()
.authenticationProvider(apiAuthenticationProvider)
.authorizeRequests()
.antMatchers(ApiInfo.BASE_URL + "/**")
.fullyAuthenticated()
.and()
.build();
}
As I did not useful answer I will post my solution.
Generally I've added custom implementation of AuthenticationEntryPoint, which handles all unauthorized request and it is proceeded after AuthenticationProvider:
#Component
public class BruteForceEntryPoint implements AuthenticationEntryPoint {
final BruteForce bruteForce;
static final String WWW_AUTHENTICATE_HEADER_VALUE = "Basic realm=\"Access to API\", charset=\"UTF-8\"";
public BruteForceEntryPoint(BruteForce bruteForce) {
this.bruteForce = bruteForce;
}
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
addWwwAuthenticateHeader(request, response);
bruteForce.incrementFailures(request.getRemoteAddr());
if (bruteForce.IsBlocked(request.getRemoteAddr())) {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
OutputStream responseStream = response.getOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(responseStream, HttpStatus.TOO_MANY_REQUESTS);
responseStream.flush();
} else {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
OutputStream responseStream = response.getOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(responseStream, HttpStatus.UNAUTHORIZED);
responseStream.flush();
}
}
void addWwwAuthenticateHeader(HttpServletRequest request, HttpServletResponse response) {
if (isWwwAuthenticateSupported(request)) {
response.addHeader(WWW_AUTHENTICATE, WWW_AUTHENTICATE_HEADER_VALUE);
}
}
}
Config:
#Configuration
class WebSecurityConfig {
AuthenticationProvider apiAuthenticationProvider;
AuthenticationEntryPoint customAuthenticationEntryPoint;
public WebSecurityConfig(AuthenticationProvider apiAuthenticationProvider, AuthenticationEntryPoint customAuthenticationEntryPoint) {
this.apiAuthenticationProvider = apiAuthenticationProvider;
this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
}
#Bean
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
return
http
.httpBasic()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers(AapiInfo.BASE_URL + "/**").authenticated()
.and()
.authenticationProvider(apiAuthenticationProvider)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.formLogin().disable()
.logout().disable()
.build();
}

Why I get cors error when submitting a request to secured resource in spring boot?

I have implemented spring security in my app using jwt token, I have the following configuration in spring security:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(
prePostEnabled = true)
public class MSSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Autowired
private AuthEntryPointJwt unauthorizedHandler;
#Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/companies/UnAuth/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/companies/Auth/**").authenticated()
.antMatchers("/companies/Auth/Update").authenticated()
.antMatchers("/companies/Auth/Delete").authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
I have the following cors annotation on the relevant controller:
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/companies")
#Slf4j
public class CompanyController {
I tried to add the following to the http interceptor in angular:
authReq.headers.set("Access-Control-Allow-Origin", "http://localhost:4200");
authReq.headers.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
When submitting the request from Angular 9 app I can't pass the security and I get cors error:
`Access to XMLHttpRequest at 'http://localhost:9001/companies/Auth/Update' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resourc`e.
The request doesn't contain the 'Access-Control-Allow-Origin' header, you should add it in the headers, it allows remote computers to access the content you send via REST.
If you want to allow all remote hosts to access your api content you should add it like so:
Access-Control-Allow-Origin: *
Your can also specify a specific host:
Access-Control-Allow-Origin: http://example.com
You should modify your dependencies in the pom.xml file and allow CORS headers, appart from the Access-Control-Allow-Origin headers there are a few more that you will need to add to the request, seek more info here:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

Adding parameters to header does not work while implementing SpringBoot Security JWT for REST API

I'm trying to implement authentication and authorization using JWT token in SpringBoot REST API.
In my JWTAuthentication class
#Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res,
FilterChain chain, Authentication auth) throws IOException, ServletException {
String token = Jwts.builder().setSubject(((User) auth.getPrincipal()).getUsername())
.claim("roles", ((User) auth.getPrincipal()).getAuthorities())
.setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes()).compact();
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
chain.doFilter(req, res);
System.out.println("Token:"+token);
}
When I test my code by sending by posting the following message to 127.0.0.1:8080/login URL, I see that authentication is successful.
{"username":"admin", "password":"admin"}
And then Spring calls my JWT Authorization class
#Override
protected void doFilterInternal(
HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException {
String header = req.getHeader(SecurityConstants.HEADER_STRING);
if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
if (header == null) {
System.out.println("header null");
} else if (!header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
System.out.println("token prefix missing in header");
}
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
It prints the message: "token prefix missing in header"
Although I add the TOKEN_PREFIX in the successfulAuthentication method, it can not find it in the header in doFilterInternal method.
By the way, my security config is like this:
#EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired private UserDetailsService userDetailsService;
#Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// this disables session creation on Spring Security
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(
"/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
I checked the SpringBoot books but could not find a book that describes the inner details of the security framework. Since I did not understand how the framework works, I could not solve the problems by just looking at the blogs. Is there a book that you can suggest describing the details of SpringBoot Security?
Thanks
You set your token after you successfully authenticated the user to the header of
the Http response:
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
The internal JWT filter (from what I understand in your question is called after yours), looks in the Http headers of the request
String header = req.getHeader(SecurityConstants.HEADER_STRING);
and there they are not present.
In general, the second filter should not be active after you authenticated a user and should just return the JWT token to the client. Any subsequent call of the client should then include the JWT token in the Authorization header using Bearer: YourJWTToken for calling e.g. protected APIs.

Spring boot security x-auth-token not found in header

I have a spring boot application having REST services secured with spring security. Redis is used for storing sessions. I have deployed the application in Glassfish 4.1.2. When trying to login using basic auth, x-auth-token is not returned in response header. What could be the issue ?
Below are my configuration classes:
ApplicationSecurityConfig
#Configuration
#EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
#Autowired
private CustomAuthenticationDetailsSource source;
#Autowired
private HttpLogoutSuccessHandler logoutSuccessHandler;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/crr/**").access("hasRole('CRR')")
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler)
.and()
.httpBasic().authenticationDetailsSource(source).authenticationEntryPoint(authenticationEntryPoint);
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.csrf().disable();
}
}
CORSCustomFilter
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSCustomFilter implements Filter {
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"X-Requested-With,content-type, Authorization");
chain.doFilter(servletRequest, servletResponse);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
Note: When I deploy the application in Tomcat,x-auth-token is successfully generated in response header.
To retrieve it from response headers, Add x-auth-token to Access-Control-Allow-Credentials and Access-Control-Expose-Headers
response.setHeader("Access-Control-Expose-Headers", "x-auth-token");
response.setHeader("Access-Control-Allow-Credentials", "x-auth-token");
This worked for me.

Spring OAuth2 Implicit Flow - Auth server not processing the POST /oauth/authorize request

I have an authorization server (http://localhost:8082), resource server and implicit client (http://localhost:8080) project. The problem is that when the client asks for the authorization (token), the auth server shows the login screen but after the successful login it redirects to GET http://localhost:8082/ instead of to http://localhost:8082/authorize?client_id=... (as requested by the client)
I am seeing this log:
Implicit client:
.s.o.c.t.g.i.ImplicitAccessTokenProvider : Retrieving token from http://localhost:8082/oauth/authorize
o.s.web.client.RestTemplate : Created POST request for "http://localhost:8082/oauth/authorize"
.s.o.c.t.g.i.ImplicitAccessTokenProvider : Encoding and sending form: {response_type=[token], client_id=[themostuntrustedclientid], scope=[read_users write_users], redirect_uri=[http://localhost:8080/api/accessTokenExtractor]}
o.s.web.client.RestTemplate : POST request for "http://localhost:8082/oauth/authorize" resulted in 302 (null)
o.s.s.web.DefaultRedirectStrategy : Redirecting to 'http://localhost:8082/login?client_id=themostuntrustedclientid&response_type=token&redirect_uri=http://localhost:8080/api/accessTokenExtractor'
Auth Server:
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/authorize' doesn't match 'GET /**
o.s.s.w.util.matcher.AndRequestMatcher : Did not match
o.s.s.w.s.HttpSessionRequestCache : Request not saved as configured RequestMatcher did not match
o.s.s.w.a.ExceptionTranslationFilter : Calling Authentication entry point.
o.s.s.web.DefaultRedirectStrategy : Redirecting to 'http://localhost:8082/login'
The implicit client is POSTing for /oauth/authorize, instead of GETting it, and the authserver doesn't store POST requests. The auth server returns a redirect 302 and the implicit client redirects the browser to this url: http://localhost:8082/login?client_id=themostuntrustedclientid&response_type=token&redirect_uri=http://localhost:8080/api/accessTokenExtractor
After successful login the auth server doesn't have a target url so it shows http://localhost:8082/ so it doesn't process any /oauth/authorize request... Where is the problem?
AUTH SERVER CONFIG:
#Configuration
class OAuth2Config extends AuthorizationServerConfigurerAdapter{
#Autowired
private AuthenticationManager authenticationManager
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("themostuntrustedclientid")
.secret("themostuntrustedclientsecret")
.authorizedGrantTypes("implicit")
.authorities("ROLE_USER")
.scopes("read_users", "write_users")
.accessTokenValiditySeconds(60)
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(this.authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//security.checkTokenAccess('hasRole("ROLE_RESOURCE_PROVIDER")')
security.checkTokenAccess('isAuthenticated()')
}
}
#Configuration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("jose").password("mypassword").roles('USER').and()
.withUser("themostuntrustedclientid").password("themostuntrustedclientsecret").roles('USER')
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
//
//XXX Si se usa implicit descomentar
.ignoringAntMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
//.httpBasic()
.formLogin()
.loginPage("/login").permitAll()
}
}
IMPLICIT CLIENT CONFIG:
#Configuration
class OAuth2Config {
#Value('${oauth.authorize:http://localhost:8082/oauth/authorize}')
private String authorizeUrl
#Value('${oauth.token:http://localhost:8082/oauth/token}')
private String tokenUrl
#Autowired
private OAuth2ClientContext oauth2Context
#Bean
OAuth2ProtectedResourceDetails resource() {
ImplicitResourceDetails resource = new ImplicitResourceDetails()
resource.setAuthenticationScheme(AuthenticationScheme.header)
resource.setAccessTokenUri(authorizeUrl)
resource.setUserAuthorizationUri(authorizeUrl);
resource.setClientId("themostuntrustedclientid")
resource.setClientSecret("themostuntrustedclientsecret")
resource.setScope(['read_users', 'write_users'])
resource
}
#Bean
OAuth2RestTemplate restTemplate() {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), oauth2Context)
//restTemplate.setAuthenticator(new ApiConnectOAuth2RequestAuthenticator())
restTemplate
}
#Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.eraseCredentials(false)
.inMemoryAuthentication().withUser("jose").password("mypassword").roles('USER')
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringAntMatchers("/accessTokenExtractor")
.and()
.authorizeRequests()
.anyRequest().hasRole('USER')
.and()
.formLogin()
.loginPage("/login").permitAll()
}
}
The problem was in the SecurityConfig of the Auth server. The implicit client sends automatically a basic Authorization header with the client_id and client_secret. My Auth server was configured to use form login instead of basic auth. I changed it and now it works as expected:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
//
//XXX Si se usa implicit descomentar
.ignoringAntMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()

Resources