Spring disable security for tests


  • Using the H2 Database Console in Spring Boot with Spring Security
  • Spring Microservices Security Best Practices
  • Securing Applications using Spring Boot Keycloak Integration – Part 2
  • 10 Spring Boot security best practices
  • Final thoughts 1. It acts as a single entry point into the whole system. It is responsible not only for request routing but also for several other things including security. Consequently, one of the most essential components of security we should enable on the gateway is rate limiting. On the other hand, Spring Cloud Gateway comes with a built-in implementation of a rate limiting component. To sum up, you just need to include a single dependency to build a gateway application.

    Then you have to provide some configuration settings to enable rate limiting for a single route. In order to enable a rate limiter on a gateway, we need to use a component called RequestRateLimiter GatewayFilter factory. It uses a RateLimiter implementation to determine if the current request is allowed to proceed. The RequestRateLimiter implementation uses Redis as a backend. There are three parameters that can be used to configure the rate limiter: replenishRate, burstCapacity, and requestedTokens.

    The replenishRate property is how many requests per second a single user may send. The burstCapacity property is the maximum number of requests a user can send in a single second. With the requestedTokens property, we may set the cost of a single token. A rate limiter defines all parameters per a single key returned by the resolver.

    Generate and propagate certificates dynamically Should we use SSL in microservice to microservice communication? Of course yes. But the question is how will you handle certificates used by your microservices. There are several best practices related to SSL certificate management. For example, you should not issue certificates for long time periods.

    You should also automatically renew or refresh them. There are some tools that can help in following best practices. One of the most popular of them is Vault from Hashicorp. It provides the PKI secrets engine, which is responsible for generating dynamic X. The simplest way to try vault is to run it locally on a Docker container. The fragment of code visible below shows how to create a certificate request with 12h TTL and localhost as a Common Name.

    Then we will invoke the issueCertificate method on the VaultPkiOperations object. The generated CertificateBundle contains both certificate and private key. The default behavior of our webserver needs to be overridden.

    Depending on the webserver we need to customize a different WebServerFactory. NEED ; ssl. Use SSL in microservices communication Since using SSL on the edge of a microservices-based system is obvious, inter-service communication is sometimes considered to be non-secure.

    My recommendation is always the same. One of them will probably be a config server. Since it is built on top of Spring MVC we may easily enable a secure connection on the server-side. Since it is responsible for connecting with the server, we also need to handle SSL there.

    The fragment of code visible below uses a self-signed certificate, but we can easily implement here a strategy described in the previous section. We just need to define the right settings using properties with a prefix spring. What about encrypting communication between applications and a discovery server? You can choose between several available discovery servers support in Spring Cloud.

    Similarly to Spring Cloud Config we use a high-level client to communicate with a server. Bean public DiscoveryClient. Since we use RestTemplate or WebClient instances directly on the client-side it is relatively easy to implement secure communication in that case. Keep configuration data encrypted The current one of best practices for Spring microservices security is related to a configuration server. We should encrypt at least sensitive data like passwords or secrets stored there.

    Spring Cloud Config Server provides a built-in mechanism for that. But we can as well use Vault as a backend store for Spring Cloud Config Server, where all data is encrypted by default. We will start with a default encrypt mechanism provided by Spring Cloud Config Server. Firstly, we need to enable it in the configuration properties. To do that you should enable a Spring profile called vault. Restrict access to the API resources In the previous sections, we discussed such topics as authentication, traffic, and data encryption.

    But another important aspect of securing your applications is authorization and access to the API resources. If you think about web app authorization, the first approach that probably comes to your mind is OAuth 2. OAuth 2. Of course, it is supported by Spring Security. There are also multiple OAuth2 providers you can integrate your application with.

    One of them is Keycloak. I will use it in the example in this article. By default, it exposes API and a web console on port Besides spring-cloud-starter-gateway dependency, we need to include spring-boot-starter-oauth2-client and spring-cloud-starter-security to activate the TokenRelay filter.

    Then we have to provide the Spring Security configuration settings for the OAuth2 client. Inside the filterChain method we are going to enable authorization for all the exchanges. A Token Relay is where an OAuth2 consumer acts as a Client and forwards the incoming token to outgoing resource requests. It a single ping method. That method may be accessed only by the client with the TEST scope. Dynamically generate credentials to the external systems Does your application connect to external systems like databases or message brokers?

    How do you store the credentials used by your application? Of course, we can always encrypt sensitive data, but if we work with many microservices having separate databases it may not be a very comfortable solution. Here comes Vault with another handy mechanism. Its database secrets engine generates database credentials dynamically based on configured roles.

    Therefore, we need to configure a Vault plugin for PostgreSQL database and then provide connection settings and credentials. We also have to set a target database name and SQL statement that creates users with privileges. Two dependencies need to be included in Maven pom.

    Of course, we also need dependencies for the JPA and Postgres driver. The following configuration settings should be placed in bootstrap. You may consider running thje application on Nomad.

    Always be up to date This one of the best practices may be applied anywhere not only as a rule to Spring microservices security. We usually use open-source libraries in our applications, so it is important to include the latest versions of them. Final thoughts That is my private list of best practices for Spring Boot microservices security. Of course, most of them are not related just to a single framework, and we apply them for any other framework or toolkit.

    Do you have your own list of Spring Security best practices? Share this:.

    Others Full source code of this example on GitHub. Spring applications are not secured by default. To provide required authentication and authorization facilities you need to either create them from the scratch or use existing security framework. Writing such a framework from the scratch is almost never a good idea. Better idea is to use some existing, matured and proven frameworks. The natural choice for Springers is to use Spring-Security.

    Formerly known as Acegi Security, later incorporated under the umbrella of Spring components, Spring-Security is just a jar file that you include in the software development project. It provides you with vast amount of well-designed functionality ready to be applied to your application.

    It is a framework that gives you a lot but on the other side it is still quite complicated, mainly, due to a lot of working parts and general nature of security related mechanisms. Spring-Security is also extremely extensible and open for customization, extensions and fine-tune configuration. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

    Creates Spring-Boot project, provides simple config in Maven or Gradle, drops dependencies on required libraries and baam! If Spring-Boot with autoconfiguration enabled detects Spring-Security jar on the classpath it will configure and enable security using default options.

    Spring Java Config is just an approach to configure everything by using Java classes. So say no to xml files and move into statically typed, compiler safe, refactorable world of Java classes, methods and annotations. And things are looking good here especially with Servlet 3.

    Spring-Boot prefers Java config and I will try to use it as much as possible. Spring Integration Testing is Spring support for writing proper integration tests. Spring-Boot brings its own improvements and as Boot by default is using embedded container like Tomcat or Jetty, writing integration tests is really awesome. We will use such tests to check if our security mechanisms are working as expected.

    Such cross cutting concerns can really obscure the core business code with infrastructure related one, especially if you have more than one such concern. And usually you do have more than one. Spring-Security when developing Spring web applications for example Spring MVC adds quite a few http filters that delegate to authentication and authorization components.

    Moreover,it provides aspects that wrap around selected core business functionality using AOP. This approach keeps business code almost entirely free of any security related, infrastructural stuff. We can think about security as kind of add-on that can be applied or removed to existing code base. This, of course, makes everything nicely decoupled and isolated, which leads to much more clean, readable and maintainable code. So Spring-Security adds a lot of filters.

    Filter can do whatever it wants to the request, it can even totally change request parameters. When filter is done with processing, it can do one of two things. It can pass probably modified http request to the next filter or it can stop processing and return HTTP Response. Filter that allowed request to be processed will also process HTTP Response that was generated by other components.

    So it can change response as well. Filters can be chained and assuming that each filter allowed request to be processed by the next filter such a request finally ends up in Spring DispatcherServlet and gets routed to our Java controller methods.

    Spring-Security provides a handy couple of filters in its default filter chain. A lot of them provide out-of-the box security functionality for many of security schemes currently used in the world, e. In this blog and code I will provide my own filter and attach it somewhere in the default Spring-Security filter chain. This request has no authentication credentials of any sort, so it is anonymous, random call.

    As the request has no credentials, Spring filters will pass it through without any special processing. Such a request will land at AbstractSecurityInterceptor, which in conjunction with AccessDecisionManager will determine target resource and method, and then makes a decision whether or not such unauthenticated request is allowed to access this resource. Security configuration determines if it is allowed or not and what particular roles authenticated user must have to access the resource authorization.

    In our case we assume that the resource requires user to be authenticated, so AbstractSecurityInterceptor will throw some subclass of AuthenticationException.

    This exception will be caught by ExceptionTranslationFilter which is one of many filters in the default security chain. ExceptionTranslationFilter will validate type of the exception and if it indeed is AuthenticationException it will delegate call to AuthenticationEntryPoint component.

    Client can then respond. Browsers display a dialog for the user to enter username and password, other clients can do different things to obtain such credentials. The result is the same, another request for the same resource, but with credentials in proper HTTP Headers. This time Spring filters have a lot more to do.

    First, they extract credentials and use them to build Authentication object that acts as input for further processing. This Authentication is passed to AuthenticationManager that asks its configured and attached AuthenticationProviders, if any of them can process such type of Authentication UsernamePasswordAuthentication.

    By default, there is such provider for Basic and it will query UserDetailsService for UserDetails object corresponding for such username. This UserDetails will then be validated against password and if everything is present, matches and is otherwise correct, new output Authentication object will be created. This output object is marked as successfully authenticated and filled with GrantedAuthorities that corresponds to the roles assigned to this particular user.

    Where are UserDetails taken from? It depends on configuration. So we have authenticated Authentication. The filter that initiated this operation will put this Authentication to SecurityContextHolder and pass the request down to the next filters.

    Any further filters will check if SecurityContextHolder holds valid Authentication and use GrantedAuthorities to do authorization validation. The same goes for AOP extended methods of our controllers if we decide to use this approach. Our code does not need to interact with SecurityContextHolder but if it needs to have some authentication information, it must.

    If we use direct access, it will make our testing life much more complicated so there are ways to minimize this impact that I will show later. Oh, by the way, SecurityContextHolder uses ThreadLocal under the hood and is filled and cleared on per request basis. Looks complicated? Unfortunately, there is no good default flow for securing REST calls using token based approach, unless you can use OAuth 2. A lot of security code is quite generic and will work with any external service authentication mechanism.

    I have added some exemplaryexample implementation that does not do any network calls and it is easy to extend it to suit your needs. The build management tool is Gradle and in a build. The important parts are spring-boot-starter-security and spring-boot-starter-test: compile 'org.

    So by default, our tokens will be evicted after 4 hours since issue time. Such certificate is good for development and testing or maybe even for intranet services but you should use properly signed one for any other use case. You can override this certificate by properties at deployment time. The properties are in application. Configuration — tells Spring that this class will act as a configuration source. There can be many such classes.

    ComponentScan — enables autoscanning and processing of all Spring components in current and descendant packages. EnableAutoConfiguration — tells Spring-Boot to try to autoconfigure itself by using default values. Any our custom parts replace the defaults. EnableConfigurationProperties — it allows having beans annotated with ConfigurationProperties that is beans that will be filled with properties from various sources.

    No xmls, no web. ApiController is base class for all Controllers. I have added two Controllers. This method however will never be entered because of our implementation of AuthenticationFilter, which will be described in a moment. The method is yet still present to become part of documentation for both in-code and REST services for example using Swagger. It states that all mapped methods will produce direct response output using ResponseBody.

    The default mapping is JSON so this is exactly what we need. PreAuthorize annotation is very important for this example. SecurityContextHolder will be queried to get this information.

    For PreAuthorize annotation to have effect there is a need to have EnableGlobalMethodSecurity annotation on Configuration bean somewhere.

    I will get to this soon. PreAuthorize security is one of the simplest ways to protect our resources. For our example use-case you could use URL request protection in configuration, which is even simpler but I have decided to show this method as well.

    These methods are simple but they are clean, easy to see and maintain and this should be our goal as much as possible. We are also autowiring implementation of Gateway to some service, so controller code will not be obscured by implementation details.

    It will allow us to test it later with ease. There may be a need to have some details regarding currently authenticated principal. If we would directly use SecurityContextHolder static context with ThreadLocal to get this information we would make unnecessary coupling to some internal concern and our code would be much harder to test.

    There is however a neat way to obtain the information we need. What is that?

    ExceptionTranslationFilter will validate type of the exception and if it indeed is AuthenticationException it will delegate call to AuthenticationEntryPoint component. Client can then respond. Browsers display a dialog for the user to enter username and password, other clients can do different things to obtain such credentials.

    The result is the same, another request for the same resource, but with credentials in proper HTTP Headers. This time Spring filters have a lot more to do. First, they extract credentials and use them to build Authentication object that acts as input for further processing.

    Using the H2 Database Console in Spring Boot with Spring Security

    This Authentication is passed to AuthenticationManager that asks its configured and attached AuthenticationProviders, if any of them can process such type of Authentication UsernamePasswordAuthentication.

    By default, there is such provider for Basic and it will query UserDetailsService for UserDetails object corresponding for such username. This UserDetails will then be validated against password and if everything is present, matches and is otherwise correct, new output Authentication object will be created.

    This output object is marked as successfully authenticated and filled with GrantedAuthorities that corresponds to the roles assigned to this particular user. Where are UserDetails taken from? It depends on configuration. So we have authenticated Authentication. The filter that initiated this operation will put this Authentication to SecurityContextHolder and pass the request down to the next filters.

    Any further filters will check if SecurityContextHolder holds valid Authentication and use GrantedAuthorities to do authorization validation. The same goes for AOP extended methods of our controllers if we decide to use this approach. Our code does not need to interact with SecurityContextHolder but if it needs to have some authentication information, it must. If we use direct access, it will make our testing life much more complicated so there are ways to minimize this impact that I will show later.

    Oh, by the way, SecurityContextHolder uses ThreadLocal under the hood and is filled and cleared on per request basis. Looks complicated? Unfortunately, there is no good default flow for securing REST calls using token based approach, unless you can use OAuth 2. A lot of security code is quite generic and will work with any external service authentication mechanism. I have added some exemplaryexample implementation that does not do any network calls and it is easy to extend it to suit your needs.

    The build management tool is Gradle and in a build. The important parts are spring-boot-starter-security and spring-boot-starter-test: compile 'org. So by default, our tokens will be evicted after 4 hours since issue time.

    Spring Microservices Security Best Practices

    Such certificate is good for development and testing or maybe even for intranet services but you should use properly signed one for any other use case. You can override this certificate by properties at deployment time.

    The properties are in application. Configuration — tells Spring that this class will act as a configuration source. There can be many such classes. ComponentScan — enables autoscanning and processing of all Spring components in current and descendant packages. EnableAutoConfiguration — tells Spring-Boot to try to autoconfigure itself by using default values. Any our custom parts replace the defaults. EnableConfigurationProperties — it allows having beans annotated with ConfigurationProperties that is beans that will be filled with properties from various sources.

    Securing Applications using Spring Boot Keycloak Integration – Part 2

    No xmls, no web. ApiController is base class for all Controllers. I have added two Controllers. This method however will never be entered because of our implementation of AuthenticationFilter, which will be described in a moment.

    The method is yet still present to become part of documentation for both in-code and REST services for example using Swagger. It states that all mapped methods will produce direct response output using ResponseBody. The default mapping is JSON so this is exactly what we need.

    PreAuthorize annotation is very important for this example. SecurityContextHolder will be queried to get this information. For PreAuthorize annotation to have effect there is a need to have EnableGlobalMethodSecurity annotation on Configuration bean somewhere. I will get to this soon. PreAuthorize security is one of the simplest ways to protect our resources.

    For our example use-case you could use URL request protection in configuration, which is even simpler but I have decided to show this method as well. These methods are simple but they are clean, easy to see and maintain and this should be our goal as much as possible.

    We are also autowiring implementation of Gateway to some service, so controller code will not be obscured by implementation details. It will allow us to test it later with ease. There may be a need to have some details regarding currently authenticated principal. If we would directly use SecurityContextHolder static context with ThreadLocal to get this information we would make unnecessary coupling to some internal concern and our code would be much harder to test.

    There is however a neat way to obtain the information we need. What is that? I just like my name better than AuthenticationPrincipal. Any Spring Controller that has a method with parameter annotated with that will get current SecurityContextHolder Authentication. This is much more testable and clean. DomainUser and Stuff are simple Java beans, nothing interesting here. Security filters with filter chain are configured and applied. AuthenticationPrincipal annotation starts working. Basically, after this annotation alone our MVC services are not directly accessible anymore.

    EnableScheduling allows to run Spring schedulers and periodically run some tasks. We use scheduler for evicting EhCache tokens. We authorize requests on Spring-Actuator endpoints to any principal that has role of backend administrator and we require all other requests to be authenticated. Just authenticated — this config will pass the request to DispatcherServlet for any valid Authentication in SecurityContext.

    These filters are main building blocks of our custom token based authentication. For any AuthenticationException we want to return the error. How they handle it is up them. At this moment security config is in place and each request needs to pass through AuthenticationFilter and ManagementEndpointAuthenticationFilter.

    It tries to be as generic as possible, delegating real work to external implementations. This is our place in filter chain and it seems like excellent place to initiate some authentication facilities and work with SecurityContextHolder. It happens that we have such custom provider. Provider tries to authenticate. We expect returned output Authentication instance which can be, and usually is, a different class and instance than input Authentication to not be null and be authenticated.

    No other filter down the chain is called so no controller method is executed. It would be better to pass the request to AuthenticationController and to allow it to return the token and OK Status, but I just wanted to demonstrate a point. If call is not for authenticating endpoint, we check whether we have token in header.

    If there is a token, we move to another processing path. In any other case, no authenticate post and lack of token we pass call further to the dispatcher. This may sound strange. Why are we passing our request? But it is actually how spring security is designed. There may be some services that do not require authentication or a call may be for some static resource like icon. Nonetheless, any security violation lack of SecurityContextHolder will result in spring AuthenticationException to be thrown, caught by ExceptionTranslationFilter and our unathorizedEntryPoint called.

    But if token is present, we try to fill SecurityContextHolder with authenticated Authentication. So we prepare proper input Authentication this time of type PreAuthenticatedAuthenticationToken and pass it again to AuthenticationManager that will call proper Provider.

    This provider will try to validate token and decide if it is OK or not. Again, the result must be properly filled and authenticated output Authentication. ManagementEndpointAuthenticationFilter is very similar to AuthenticationFilter but it does not make use of tokens. It has hardcoded backend admin login username with password provided from property at deployment time. It checks if username and password from headers matches these when targeting Spring-Actuator endpoints that require authentication.

    Authenticate method tries to authenticate user by username and password. It validates parameters presence and delegates to implementation of a real provider coming from external service. Similarly to Spring Cloud Config we use a high-level client to communicate with a server. Bean public DiscoveryClient. Since we use RestTemplate or WebClient instances directly on the client-side it is relatively easy to implement secure communication in that case.

    Keep configuration data encrypted The current one of best practices for Spring microservices security is related to a configuration server. We should encrypt at least sensitive data like passwords or secrets stored there. Voyforums moms spanking talk Cloud Config Server provides a built-in mechanism for that.

    But we can as well use Vault as a backend store for Spring Cloud Config Server, where all data is encrypted by default. We will start with a default encrypt mechanism provided by Spring Cloud Config Server. Firstly, we need to enable it in the configuration properties. To do that you should enable a Spring profile called vault. Restrict access to the API resources In the previous sections, we discussed such topics as authentication, traffic, and data encryption. But another important aspect of securing your applications is authorization and access to the API resources.

    If you think about web app authorization, the first approach that probably comes to your mind is OAuth 2. OAuth 2. Of course, it is supported by Spring Security. There are also multiple OAuth2 providers you can integrate your application with.

    10 Spring Boot security best practices

    One of them is Keycloak. I will use it in the example in this article. By default, it exposes API and a web console on port Besides spring-cloud-starter-gateway dependency, we need to include spring-boot-starter-oauth2-client and spring-cloud-starter-security to activate the TokenRelay filter.

    Then we have to provide the Spring Security configuration settings for the OAuth2 client. Inside the filterChain method we are going to enable authorization for all the exchanges.

    A Token Relay is where an OAuth2 consumer acts as a Client and forwards the incoming token to outgoing resource requests. It a single ping method. That method may be accessed only by the client with the TEST scope. Dynamically generate credentials to the external systems Does your application connect to external systems like databases or message brokers?

    How do you store the credentials used by your application? Of course, we can always encrypt sensitive data, but if we work with many microservices having separate databases it may not be a very comfortable solution. Here comes Vault with another handy mechanism. Its database secrets engine generates database credentials dynamically based on configured roles.

    Therefore, we need to configure a Vault plugin for PostgreSQL database and then provide connection settings and credentials. We also have to set a target database name and SQL statement that creates users with privileges. Two dependencies need to be included in Maven pom. Of course, we also need dependencies for the JPA and Postgres driver.

    The following configuration settings should be placed in bootstrap. You may consider running thje application on Nomad. Always be up to date This one of the best practices may be applied anywhere not only as a rule to Spring microservices security. We usually use open-source libraries in our applications, so it is important to include the latest versions of them.

    Final thoughts That is my private list of best practices for Spring Boot microservices security. Of course, most of them are not related just to a single framework, and we apply them for any other framework or toolkit. Do you have your own list of Spring Security best practices?


    thoughts on “Spring disable security for tests

    • 18.09.2021 at 10:10
      Permalink

      Do not despond! More cheerfully!

      Reply
    • 18.09.2021 at 19:17
      Permalink

      I think, that you are not right. I am assured. Let's discuss. Write to me in PM, we will communicate.

      Reply
    • 23.09.2021 at 21:51
      Permalink

      Excuse for that I interfere � At me a similar situation. It is possible to discuss. Write here or in PM.

      Reply
    • 26.09.2021 at 04:30
      Permalink

      I think, that you commit an error. Write to me in PM, we will discuss.

      Reply

    Leave a Reply

    Your email address will not be published. Required fields are marked *