In what package is now located the .csrf() method in Spring 5? - spring

I am trying to write an IT.
mockMvc.perform( post( "/my_endpoint" )
.contentType( MediaType.APPLICATION_JSON )
.header("Authorization", my_credentials)
.with(csrf())
.content( jsonPayload )
)
.andExpect( status().isOk() );
I need to import the csrf() static method, but the package where usually was founded (org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors...) no longer exists.
Some fresh idea on how can I write a csrf protection to avoid a 403 on the test?
Thanks.

To use the Spring Security test support, you must include spring-security-test-5.1.2.RELEASE.jar as a dependency of your project.
And give a try below:-
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProce ssors.*;
mvc.perform(post("/").with(csrf()))
or,
mvc.perform(post("/").with(csrf().asHeader()))
or,
mvc.perform(post("/").with(csrf().useInvalidToken()))

You can use it as follows
csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

My answer is based on the Spring Reactive. Spring Boot :2.6.1
Add below entry in build.gradle
testImplementation 'org.springframework.security:spring-security-test'
And then, csrf() method will be available from below import
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;

Related

How to register custom filter in micronaut?

I am trying to register custom filter in micronaut, but I don't find any FilterRegistrationBean kind of classes we have in Spring to register our own filter. I went through the micronaut documentation, but not much help for custom filter.
https://docs.micronaut.io/latest/guide/index.html#filters
Any pointers please?
I am trying to register custom filter in micronaut, but I don't find
any FilterRegistrationBean kind of classes we have in Spring to
register our own filter.
They don't really need to be registered, at least not in the way you would with Spring. If the filter is marked with #Filter and is on the CLASSPATH, it will be registered. One of the examples in the docs you linked looks like this:
import io.micronaut.http.*;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.filter.*;
import org.reactivestreams.Publisher;
#Filter("/hello/**")
public class TraceFilter implements HttpServerFilter {
private final TraceService traceService;
public TraceFilter(TraceService traceService) {
this.traceService = traceService;
}
​#Override
​public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
​return traceService.trace(request)
​.switchMap(aBoolean -> chain.proceed(request))
​.doOnNext(res ->
​res.getHeaders().add("X-Trace-Enabled", "true")
​);
}
}
No additional step is required to put that in play.
I hope that helps.

I am getting a compile time error when trying to implement the hateos , It is not showing me the methodOn method

I am trying to implement the Hateoas using spring boot.
In my UserController class i have used the below code
#GetMapping("/users/{id}")
public Resource<User> retrieveUser(#PathVariable int id) {
User user = service.findOne(id);
Resource<User> resource = new Resource<User>(user);
ControllerLinkBuilder linkTo=linkTo(methodOn(this.getClass()).retrieveAllUsers());
I am getting a compile time error on line where i am using the - methodOn().
Compiler is not able to find the methodOn using the controller link builder.
I have used the below import to implement hateoas
import org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
Methods you are using here are static, so to use them you need access using class reference unless you import them using static imports. See more details here

Testing Spring Boot rest controller, unable to locate package for is()

I'm writing a test for a REST controller in Spring Boot. Is uses is(), but my IDE is not suggesting what package this is in so I'm unable to find it.
Here's my test method;
#Test
public void printerIsReady() throws Exception {
/* Set the contents of status.txt to anything other than 3 */
String statusFilePath = printerPath + "/status.txt";
PrinterFileHelper.writeToFile("5", statusFilePath);
this.mockMvc.perform(get("/printer"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status", is("READY")));
}
I'm finding a lot of examples online that use the is() method, but it's not clear at all what package I need to be adding in order to access it.
I found the answer here How to check String in response body with mockMvc
The package you need to import is;
import static org.hamcrest.Matchers.*;
I needed to add the package to my pom.xml file
<dependency>
<groupId>org.testinfected.hamcrest-matchers</groupId>
<artifactId>core-matchers</artifactId>
<version>1.5</version>
</dependency>

Configuring Spring MockMvc to use custom argument resolver before built-in ones

I have a straightforward test case. I have a controller which has a parameter of a type Spring doesn't support by default, so I wrote a custom resolver.
I create the mock mvc instance I'm using like so:
mvc = MockMvcBuilders.standaloneSetup(controller).setCustomArgumentResolvers(new GoogleOAuthUserResolver()).build();
However, Spring is also registering almost 30 other argument resolvers, one of which is general enough that it is getting used to resolve the argument before mine. How can I set or sort the resolvers so that mine is invoked first?
This worked for me without reflection:
#RequiredArgsConstructor
#Configuration
public class CustomerNumberArgumentResolverRegistration {
private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;
#PostConstruct
public void prioritizeCustomArgumentResolver () {
final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(Objects.requireNonNull(requestMappingHandlerAdapter.getArgumentResolvers()));
argumentResolvers.add(0, new CustomerNumberArgumentResolver());
requestMappingHandlerAdapter.setArgumentResolvers(argumentResolvers);
}
}
The issue was that the People class the Google OAuth library I am using extends Map and the mock servlet API provides no way to manipulate the order in which the handlers are registered.
I ended up using reflection to reach into the mocks guts and remove the offending handler.

Swagger endpoint not accessible

I have a spring mvc project that uses gradle to build the project.
I used the steps described here in this project.
The build.gradle file has the following entry for swagger:
compile (libraries.swagger){
exclude group:'org.slf4j', module:'slf4j-log4j12'
exclude group:'org.slf4j', module:'slf4j-api'
exclude group:'junit', module:'junit'
}
The configuration for swagger is done in the project build.gradle as below:
swagger: "com.knappsack:swagger4spring-web:0.3.3"
My controller for the documetation end point is:
import com.knappsack.swagger4springweb.controller.ApiDocumentationController;
import com.wordnik.swagger.model.ApiInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* This is an example of how you might extend the ApiDocumentationController in order to set your
* own RequestMapping (instead of the default "/api") among other possibilities. Going this route,
* you do not necessarily have to define the controller in your servlet context.
*/
#Controller
#RequestMapping(value = "/documentation")
public class SwaggerDocumentationController extends ApiDocumentationController {
public SwaggerDocumentationController() {
setBaseControllerPackage("com.controller");
setBaseModelPackage("com.domain");
setApiVersion("v1");
ApiInfo apiInfo = new ApiInfo("swagger",
"This is a basic web app for demonstrating swagger",
"http://localhost:9999/terms", "http://localhost:9999/contact", "MIT",
"http://opensource.org/licenses/MIT");
setApiInfo(apiInfo);
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String documentation() {
return "documentation";
}
}
And then I try to access the endpoints for documentation as: http://localhost:9999/myApp/documentation/test
test is the mapping mentioned inside the controller like below:
#Api(value = "test",
description = "A test controller to see if the services are up and running.")
#RequestMapping(value = {"/test"}, method = {RequestMethod.GET})
I get a 404 not found error while accessing the documentation URL above. Am I missing something?
Please do let me know if any more information is required.
Please help !!
I have user swagger-springmvc and its working fine. You can try it from following url
https://github.com/martypitt/swagger-springmvc

Resources