Custom render of Spring Oauth2 errors - spring

How can I change the render of Spring Oauth2 errors? For example when you try to access rest resource which is protected without providing Bearer header, this error is rendered by Spring Framework :
<oauth>
<error_description>Full authentication is required to access this resource</error_description>
<error>unauthorized</error>
</oauth>
I want it to render like my other API responses and error messages which I am handling with #ControllerAdvice and #ExceptionHandler annotations.
I have tried to provide WebResponseExceptionTranslator but it only triggers when I provide bad credentials.
I see that the DefaultOAuth2ExceptionRenderer is responsible for rendering this errors, but could not manage to change it.

Related

How to access Request headers in Spring Web services PayloadValidatingInterceptor

I am currently working on a Spring Web services(SOAP) project. The requirement is to validate the request payload and return the error response if validation fails and log it. I have extended PayloadValidatingInterceptor to return custom validation message.
As part of logging requirement, we need to print the header values from Request Headers (HttpServletRequest) for tracking purpose.
How to access HttpServletRequest in the implementation of PayloadValidatingInterceptor?
Is it possible to inject HttpServletRequest?
version details:
Spring-Boot : 2.2.6
Spring-ws-core : 3.0.8
Please help.

Inspect request body within a spring security filter

Basic Spring Security is great as it comes with WebSecurity (preventing malformed URLs) along with setting up authentication and authorization.
As part of authenticating my web request, the digest of the request body needs to be verified against the digest value passed in the http header. Setting up the Spring Security filter, forces my auth filter to process a firewalled request. The firewalled request doesn't seem to expose the request body to the filter.
What is the correct way to set up the Spring Security filter so that I can inspect the request body?
Thanks!
In Spring Security there are many filter classes built in for to be extended and used for specific purposes. As in my experience most of (or all of them) have methods with overloads which have access to,
HttpServletRequest request, HttpServletResponse response
as method arguments, so that those can be used inside the method.
When the filter class is met with any request, these variables are then populated with related data thus the code inside the methods output as expected.

Spring security exception handler

I have spring oauth2 authorization server with authorization_code and refresh_token grant types client. Sometimes it happens that used refresh_token is not valid, which causes long and ugly exception in logs:
org.springframework.security.oauth2.common.exceptions.InvalidGrantException: Invalid refresh token: xxxxxxxx-yyyy-xxxx-yyyy-xxxxxxxxxxxx
at org.springframework.security.oauth2.provider.token.DefaultTokenServices.refreshAccessToken(DefaultTokenServices.java:142) ~[spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
at org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter.getAccessToken(RefreshTokenGranter.java:47) ~[spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.grant(AbstractTokenGranter.java:65) ~[spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
at org.springframework.security.oauth2.provider.CompositeTokenGranter.grant(CompositeTokenGranter.java:38) ~[spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
[...]
Is it there anything like #RestControllerAdvice which would handle such exceptions?
I already tried using mentioned #RestControllerAdvice, but unfortunately it didn't work.
I am not very familiarized with Spring OAUTH2 Authorization, however my answer might be helpful for you.
#RestControllerAdvice is designed to assist #RestController therefore it works if the request is handled by the DispatcherServlet. However, security-related exceptions occurs before that as it is thrown by Filters. Hence, it is required to insert a custom filter AccessDeniedHandler implementation and AuthenticationEntryPoint implementation) earlier in the chain to catch the exception and return accordingly. These filters can be inserted easily in your web security configurations.
Here you can learn how to detect an Authentication Failure in the Client.
You could also check this tutorial .

Spring Boot Restful throwing unauthorised when it should throw HttpMethodNotSupported

I have a Spring Boot application with Spring Security applied in it. It is throwing 401-Unauthorised when I call a GET API with POST method.
I have used a custom authentication filter which extends UsernamePasswordAuthenticationFilter.
I have given http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); in my security config. If I comment this out, it gives me 403-Forbidden.
Can someone help with this, it should throw method not supported error. Is there any global configuration which I need to apply?

404 when do logout in Spring Security Rest Plugin for Grails

I'm setting the security system on my project (Grails - Angularjs) with Spring Security Rest Plugin v1.5.4 (using spring security core 2.0.0) for Grails 2.4.4. Doc about this plugin can be found here.
I'm testing the login and logout with postman chrome rest client and I'm able to do a login OK, but I'm getting a 404 when I do logout.
In the documentation clearly says:
The logout filter exposes an endpoint for deleting tokens. It will
read the token from an HTTP header. If found, will delete it from the
storage, sending a 200 response. Otherwise, it will send a 404
response
You can configure it in Config.groovy using this properties:
Config key...................................................................................Default
value
grails.plugin.springsecurity.rest.logout.endpointUrl....................../api/logout
grails.plugin.springsecurity.rest.token.validation.headerName....X-Auth-Token
So, after doing a login successfully, I tried to do a logout to that url (my_host_url/api/logout) with a GET method and sending a header X-Auth-Token with the token I got previously from login.
But I keep getting a 404. See image below
Edit: I'm setting the chain map like this (in order to get a stateless behavior):
grails.plugin.springsecurity.filterChain.chainMap = [
'/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter', // Stateless chain
'/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' // Traditional chain
]
So. What am I doing wrong here, or what am I missing?
Thanks in advance!
You missed another excerpt from the docs. It's a warning message literally before the chunk you quoted, and says:
Logout is not possible when using JWT tokens (the default strategy), as no state is kept in the server.
If you still want to have logout, you can provide your own implementation by creating a subclass of JwtTokenStorageService and overriding the methods storeToken and removeToken. Then, register your implementation in resources.groovy as tokenStorageService.

Resources