Spring Boot Restful throwing unauthorised when it should throw HttpMethodNotSupported - spring

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?

Related

How can I add few auth steps in spring boot + spring security?

I have a spring boot application with spring security. It works fine.
I call HTTP://localhost:8080/test request
AuthenticationProvider catches this request and authenticates the user.
MyController starts working
Now I need to add license checking to this chain.
I call HTTP://localhost:8080/test request
AuthenticationProvider catches this request and authenticates the user.
Somebody checks the license and redirect to the next step or returns an exception
if the 3-th step is a success - MyController starts working
I need to understand who is Somebody on 3-th step - Interceptor, Filter, or something else?
I would create a CustomAuthenticationProvider that is using the underlying default functionality for authentication and additionally does your licence checking.

Is it a good idea to handle optional JWT Authentication in Filter?

I am new to Spring Boot and my current project is a REST API developed in Spring Webflux. The goal is to have an endpoint which has an optional JWT Token, allowing you ti create things anonymously or not. But all the starter guides to Spring Security are really complicated and use Spring MVC, as far as I can tell.
Now my idea was to create a HandlerFilterFunction looking like
class AuthenticationFilter : HandlerFilterFunction<ServerResponse, ServerResponse> {
override fun filter(request: ServerRequest, next: HandlerFunction<ServerResponse>): Mono<ServerResponse> {
val authHeader = request.headers().header("Authorization").firstOrNull()
// get user from database
request.attributes()["user"] = user
return next.handle(request)
}
}
and adding it to the router {...} bean.
Is this a good idea, or should I go another router? If so, can somebody point me towards a JWT tutorial for Spring Webflux.
The Spring Security docs point to a JWT-Based WebFlux Resource Server sample in the codebase.
It's not Kotlin-based, so I also posted a sample of my own just now; hopefully, it helps get you started.
As for your question, yes, you can create a filter of your own, though Spring Security ships with a BearerTokenAuthenticationFilter that already does what your filter would likely do. The first linked sample adds this filter manually while the second sample lets Spring Boot add it.

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 .

Authentication object not found thrown by DispatcherServlet before #Preauthorize spring security annotation is applied

When i am trying to use #PreAuthorize("#accessControl.hasActivity('abc')") on spring controller method i am getting Authentication object was not found in security context.
After debugging found that DispactcherServlet is throwing this exception.
i have set SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
when i first create Authentication object and set in security context
Also tried with SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); but no luck still it does not work.
I am not able to understand why spring is servlet is throwing this exception
First, doing authentication in a Spring MVC interceptor is odd. Consider using a filter before DispatcherServlet. There is a lot of documented examples.
Secondly, SecurityContextHolder.setStrategyName re-initializes the strategy and possibly makes all previously authentications inaccessible so you must only call it once (if any time), before any authentication is made.
Thirdly, if you want to set the current authentication to be used by #PreAuthorize and are sure what you are doing, use SecurityContextHolder.getContext().setAuthentication(anAuthentication);. In most cases, there is a suitable filter in the API that already does this for you.

An Authentication object was not found in the SecurityContext

I have an application exporting web services, with a configured Spring Security SecurityFilterChain (with SecurityContextPersistenceFilter among others, which is required for the rest).
My application also uses Spring Security to secure method invocations.
I have following error when method security is triggered:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
The 2nd part requires an Authentication in SecurityContextHolder as showed in org.springframework.security.access.intercept.AbstractSecurityInterceptor (line 195):
SecurityContextHolder.getContext().getAuthentication();
But, SecurityContextPersistenceFilter removes it before method invocation is triggered, as shown in
org.springframework.security.web.context.SecurityContextPersistenceFilter (line 84)
SecurityContextHolder.clearContext();
What can I do to have this object in SecurityContextHolder when method invocation is triggered?
Thank you in advance.
I'm using Spring Security 3.0.8-RELEASE
SecurityContextHolder.clearContext() will be called only after request processing completion. So normally all your application logic code will be executed before this line, and there is no problem at all. But the problem may be present if you execute some new thread in your code (by default security context will be not propogated). If this is your case then you can try to force context propogation to child thread. If you use only one thread then make sure that all your code is covered by spring security filter chain (may be you have some custom filter that executed around spring security filter chain?).
OK, my application is placed over Apache CXF DOSGi 1.4 to generate REST endpoints. Apache CXF interceptors cause an unexpected behaviour and SecurityContextHolder.clearContext() is called before finishing the request processing.
More information about this bug can be found here.

Resources