Spring Testing OAuth2 Security Block

I started learning OAuth2 Spring Security with one week, so sorry if the question is simple. The topic seemed easy to me even until I started working on it. I am going to write tests for resting endpoints in my application. For this, I'm going to write tests for my resource classes. But my application uses OAuth2.

The first idea was to set up a separate Authorization Server that extends the AuthorizationServerConfigurerAdapter for these tests. I configured ClientDetailsService to store in memory and added InMemoryTokenService. But that does not work. Answer 401 - Unauthorized.

Now I’m only thinking about privatizing the DefaultTokenServices bean and somehow skipping the Authorization Server (but how?). I did not change anything in the "production" Resource server.

I know how to add a bearer token. I write my tests using OAuth2RestTemplate and add an access token to OAuth2ClientContext. I am creating an access token using conctructor DefaultOAuth2AccessToken (string value). I know there is a TestRestTemplate, but OAuth2RestTemplate seems better to me in this case. I am using Spring Boot, maybe this will help?

My questions: 1. Which solution is better? What is the best way to configure OAuth2 to run rest endpoint tests? How to conduct tests without authorization on the server? Maybe my understanding is inappropriate? 2 Is there a way to simulate requests to the authorization server? How to do it?

Thanks in advance for your cooperation.

I read a lot of materials, including: http://projects.spring.io/spring-security-oauth/docs/oauth2.html, but I could not find the answer anywhere.

+5
source share
1 answer

A little more information is required for an accurate answer:

1) do you write unit or integration tests?

If unit tests, you should not worry at all about the authorization server. All you need to do is configure SecurityContext correctly for your mockMvc request (or reactive equivalent).

If integration tests, Spring provides tools for this, but I will focus on unit tests, because, as I understand it, you are trying to write.

2) what versions of spring libraries do you use?

spring-security-oauth2 is deprecated and does not support unit tests, but in my answer to this other question I explained in detail how to create annotations to set up such a security context.

Starting with version 5.2 (choose the last step), Spring-Security-Test has basic support for unit testing @Controller, protected by JWT. If you use introspection or protected @Service, you will have to refer to this library, which I wrote, because the Spring-Security team decided to integrate only a small part of my work.

0
source

All Articles