title,body,link,tags,view_count,is_answered,score,answer_count
Spring Security testing with Mockito - Unable to create SecurityContext,"<p>I have written a test method to test a POST request to an API. Every time I run it it returns this error: Unable to create SecurityContext.</p>
<p>I am a beginner with Java and Spring and security (so go gentle on me). I'm taking an online course that asked us to create a recipe API then secure it with Spring Security. I have verified all of the end points with Postman, but am unable to pass a test using Mockito and mockMVC.</p>
<p>Java 11, Spring Boot 2.7.8</p>
<h1>Recipe Controller</h1>
<p>Including only the POST request here.</p>
<pre><code>package cn.RecipeAPI.Controllers;

import cn.RecipeAPI.Exceptions.NoSuchRecipeException;
import cn.RecipeAPI.Models.Recipe;
import cn.RecipeAPI.Services.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(&quot;/recipes&quot;)
public class RecipeController {
    @Autowired
    RecipeService recipeService;

    @PostMapping
    public ResponseEntity&lt;?&gt; createNewRecipe(@RequestBody Recipe recipe, Authentication authentication) {
        try {
            Recipe insertedRecipe = recipeService.createNewRecipe(recipe, authentication);
            return ResponseEntity.created(insertedRecipe.getLocationURI()).body(insertedRecipe);
        } catch (IllegalStateException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}
</code></pre>
<h1>Recipe Service</h1>
<pre><code>package cn.RecipeAPI.Services;

import cn.RecipeAPI.Exceptions.NoSuchRecipeException;
import cn.RecipeAPI.Models.CustomUserDetails;
import cn.RecipeAPI.Models.Recipe;
import cn.RecipeAPI.Models.Review;
import cn.RecipeAPI.Repositories.RecipeRepo;
import cn.RecipeAPI.Repositories.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.Authentication;

import java.util.List;
import java.util.Optional;

@Service
public class RecipeService {
    @Autowired
    RecipeRepo recipeRepo;
    @Autowired
    UserRepo userRepo;

    @Transactional
    public Recipe createNewRecipe(Recipe recipe, Authentication authentication) throws IllegalStateException {
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        recipe.setUser(userRepo.getReferenceById(userDetails.getId()));
        recipe.validate();
        recipe = recipeRepo.save(recipe);
        recipe.generateLocationURI();
        return recipe;
    }
}
</code></pre>
<h1>Recipe API Tests</h1>
<p>This class may include many unnecessary annotations and things. As I read through many Stack Overflow answers and the Spring Security documentation I tried various fixes. At this point I can't remember what's necessary and what's not.</p>
<pre><code>package cn.RecipeAPI;

import cn.RecipeAPI.Controllers.RecipeController;
import cn.RecipeAPI.Exceptions.NoSuchRecipeException;
import cn.RecipeAPI.Models.*;
import cn.RecipeAPI.Security.CustomUserDetailsService;
import cn.RecipeAPI.Security.SecurityConfig;
import cn.RecipeAPI.Services.RecipeService;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;



@WebMvcTest(RecipeController.class)
@ContextConfiguration(classes = SecurityConfig.class)
@ActiveProfiles(profiles = &quot;test&quot;)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ExtendWith(SpringExtension.class)
public class RecipeApiApplicationTests {
    @Mock
    private Authentication authentication;
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private RecipeService recipeService;
    @MockBean
    private CustomUserDetailsService customUserDetailsService;

    // I'm not sure if either of these are needed, but I'm going to leave them in for now
    @InjectMocks
    private RecipeController recipeController;
    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    public void setup() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    }

    // Create some test users
    // user for recipes
    UserMeta userMeta = UserMeta.builder().email(&quot;recipe@gmail.com&quot;).name(&quot;recipeUser1&quot;).build();
    Role role = Role.builder().role(Role.Roles.ROLE_USER).build();
    Set&lt;Role&gt; roles = Set.of(role);
    CustomUserDetails userRecipe = CustomUserDetails.builder().userMeta(userMeta).username(&quot;userRecipe&quot;).password(&quot;1234&quot;).authorities(roles).build();
    // user for reviews
    UserMeta userMeta1 = UserMeta.builder().email(&quot;review@gmail.com&quot;).name(&quot;reviewUser&quot;).build();
    CustomUserDetails userReview = CustomUserDetails.builder().userMeta(userMeta1).username(&quot;userReview&quot;).password(&quot;1234&quot;).authorities(roles).build();

    // Create some test recipes
    Review review = Review.builder().description(&quot;was just caramel&quot;).rating(3).user(userReview).build();
    Review review2 = Review.builder().description(&quot;was just egg&quot;).rating(4).user(userReview).build();

    Recipe recipe = Recipe.builder().name(&quot;test name&quot;).difficultyRating(1).minutesToMake(5)
            .ingredients(Set.of(Ingredient.builder().name(&quot;spam&quot;).amount(&quot;1 can&quot;).build()))
            .steps(Set.of(Step.builder().stepNumber(1).description(&quot;eat spam&quot;).build()))
            .locationURI(new URI(&quot;http://localhost:8080/recipes/1&quot;))
            .reviews(Set.of(review))
            .id(1L)
            .user(userRecipe)
            .build();
    Recipe recipe2 = Recipe.builder().name(&quot;test name2&quot;).difficultyRating(2).minutesToMake(6)
            .ingredients(Set.of(Ingredient.builder().name(&quot;egg&quot;).amount(&quot;1 egg&quot;).build()))
            .steps(Set.of(Step.builder().stepNumber(1).description(&quot;crack egg&quot;).build()))
            .locationURI(new URI(&quot;http://localhost:8080/recipes/2&quot;))
            .reviews(Set.of(review2))
            .id(2L)
            .user(userRecipe)
            .build();
    ArrayList&lt;Recipe&gt; recipes = new ArrayList&lt;&gt;(Arrays.asList(recipe, recipe2));

    public RecipeApiApplicationTests() throws URISyntaxException {
    }
@Test
    @Order(4)
    @WithUserDetails(value=&quot;userRecipe&quot;, userDetailsServiceBeanName=&quot;customUserDetailsService&quot;)
    public void testCreateNewRecipeSuccessBehavior() throws Exception {
        when(recipeService.createNewRecipe(any(Recipe.class), any(Authentication.class))).thenReturn(recipe);

        mockMvc.perform(post(&quot;/recipes&quot;)
                        //set request Content-Type header
                        .contentType(&quot;application/json&quot;)
                        //set HTTP body equal to JSON based on recipe object
                        .content(TestUtil.convertObjectToJsonBytes(recipe))
                )
                //confirm HTTP response meta
                .andExpect(status().isCreated())
                .andExpect(content().contentType(&quot;application/json&quot;))
                //confirm Location header with new location of object matches the correct URL structure
                .andExpect(header().string(&quot;Location&quot;, containsString(&quot;http://localhost:8080/recipes/1&quot;)))

                //confirm some recipe data
                .andExpect(jsonPath(&quot;id&quot;).value(1))
                .andExpect(jsonPath(&quot;name&quot;).value(&quot;test name&quot;))

                //confirm ingredient data
                .andExpect(jsonPath(&quot;ingredients&quot;, hasSize(1)))
                .andExpect(jsonPath(&quot;ingredients[0].name&quot;).value(&quot;spam&quot;))
                .andExpect(jsonPath(&quot;ingredients[0].amount&quot;).value(&quot;1 can&quot;))

                //confirm step data
                .andExpect(jsonPath(&quot;steps&quot;, hasSize(1)))
//                .andExpect(jsonPath(&quot;steps[0]&quot;).isNotEmpty())

                //confirm review data
                .andExpect(jsonPath(&quot;reviews&quot;, hasSize(1)))
                .andExpect(jsonPath(&quot;reviews[0].username&quot;).value(&quot;idk&quot;));
    }
}
</code></pre>
<h1>Stack trace</h1>
<pre><code>java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(setupBefore=TEST_METHOD, userDetailsServiceBeanName=&quot;customUserDetailsService&quot;, value=&quot;userRecipe&quot;)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.lambda$createTestSecurityContext$0(WithSecurityContextTestExecutionListener.java:126) ~[spring-security-test-5.7.6.jar:5.7.6]
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:73) ~[spring-security-test-5.7.6.jar:5.7.6]
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:293) ~[spring-test-5.3.25.jar:5.3.25]
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeEach(SpringExtension.java:174) ~[spring-test-5.3.25.jar:5.3.25]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$2(TestMethodTestDescriptor.java:163) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$6(TestMethodTestDescriptor.java:199) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:199) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:162) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:129) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.8.2.jar:1.8.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) ~[na:na]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) ~[na:na]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) ~[na:na]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) ~[na:na]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) ~[na:na]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) ~[na:na]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) ~[na:na]
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) ~[na:na]
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) ~[na:na]
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99) ~[na:na]
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79) ~[na:na]
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75) ~[na:na]
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) ~[na:na]
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) ~[na:na]
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33) ~[na:na]
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94) ~[na:na]
    at com.sun.proxy.$Proxy2.stop(Unknown Source) ~[na:na]
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193) ~[na:na]
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129) ~[na:na]
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100) ~[na:na]
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60) ~[na:na]
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56) ~[na:na]
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:113) ~[na:na]
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:65) ~[na:na]
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69) ~[gradle-worker.jar:na]
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74) ~[gradle-worker.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customUserDetailsService' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:874) ~[spring-beans-5.3.25.jar:5.3.25]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1358) ~[spring-beans-5.3.25.jar:5.3.25]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309) ~[spring-beans-5.3.25.jar:5.3.25]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.25.jar:5.3.25]
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.findUserDetailsService(WithUserDetailsSecurityContextFactory.java:76) ~[spring-security-test-5.7.6.jar:5.7.6]
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:58) ~[spring-security-test-5.7.6.jar:5.7.6]
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:43) ~[spring-security-test-5.7.6.jar:5.7.6]
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.lambda$createTestSecurityContext$0(WithSecurityContextTestExecutionListener.java:123) ~[spring-security-test-5.7.6.jar:5.7.6]
    ... 72 common frames omitted
</code></pre>
<h1>Other</h1>
<p>While reading through the <a href=""https://docs.spring.io/spring-security/reference/servlet/test/mockmvc/setup.html"" rel=""nofollow noreferrer"">Spring documentation on testing</a> I did see this note.
<a href=""https://i.stack.imgur.com/NmDM3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NmDM3.png"" alt=""enter image description here"" /></a></p>
<p>I tried adding spring-test-4.1.3.RELEASE to my dependencies and that made everything go wrong. It's the only place I've seen that mentioned. I removed it.</p>
<p>Is there anything else I should have included?</p>
",https://stackoverflow.com/questions/75510883/spring-security-testing-with-mockito-unable-to-create-securitycontext,"['java', 'spring', 'testing', 'spring-security']",317,True,1,2
Running Horusec with Docker Desktop in Windows 11 on a ReactJS project,"<p>I am learning Static Application Security Testing. In the course I am following the instructor is using Horusec to test SAST on a frontend project using Docker.</p>
<p>I have downloaded Docker Desktop and I want to try to use it, however the Docker command does not work on Windows.</p>
<p><strong>Docker command:</strong></p>
<p><code>docker run -v /var/run/docker.sock:/var/run/docker.sock -v $(pwd):/src horuszup/horusec-cli:latest horusec start -p /src -P $(pwd)</code></p>
<p><strong>My setup:</strong></p>
<ul>
<li>OS: Windows 11</li>
<li>Docker Desktop v4.19.0</li>
<li>Editor: Visual studio Code 1.78.2</li>
</ul>
<p>How can I adjust the command so that it works with Windows?</p>
",https://stackoverflow.com/questions/76246592/running-horusec-with-docker-desktop-in-windows-11-on-a-reactjs-project,"['reactjs', 'docker', 'devsecops']",22,False,-2,0
"Splitting a sentence at comma delimiter, but leaving commas which are present in the values","<p>I stuck at a problem where, i need to split a sentence containing multiple sentences has to be split at comma delimiter. The problem am facing is that, even the string also has commas which should not be considered as delimiter. The commas as values are present at random, so cannot have regex approach either. I think am going have to use NLP approach for this.</p>
<p>I tried regex and pattern matching but it is not able to handle all the cases, hence I think am going to have to go with NLP approach</p>
<p>Here is an example for input :-
'Reduction of manual triaging effort, Built browser based test application, Real-Time Monitoring of Audio and Video frame by frame,<em>Test Assessment, Test Design, Test Optimization</em>, Test Report and Test Bench creation, Providing high-level and low-level requirements for Automation of key modules, Test Analysis and Use-case generation and Scope identification for the CFRs, Network protocols testing and Security testing using in-home solutions and external third party tools, Effective Escape Defect Analysis strategy'</p>
<p>Output:-
[Reduction of manual triaging effort,
Built browser based test application, Real-Time Monitoring of Audio and Video frame by frame,
Test Assessment, Test Design, Test Optimization, Test Report and Test Bench creation,
Providing high-level and low-level requirements for Automation of key modules,
Test Analysis and Use-case generation and Scope identification for the CFRs,
Network protocols testing and Security testing using in-home solutions and external third party tools,
Effective Escape Defect Analysis strategy']</p>
",https://stackoverflow.com/questions/75674069/splitting-a-sentence-at-comma-delimiter-but-leaving-commas-which-are-present-in,"['nlp', 'spacy', 'named-entity-recognition']",39,False,0,0
How to secure the public external facing APIs,"<p>The below is what I can summarized the ways to secure the public facing APIs, please help to comment/answer if there's any further points, thanks so much</p>
<ol>
<li><p>API Authentication : To implement authorization mechanism. This can involve techniques such as OAuth, JSON Web Tokens (JWT), and API keys to ensure that only authorized users or applications can access the API.</p>
</li>
<li><p>Data Transit Encryption: To use safe communication protocols such as HTTPS or SSL/TLS To protect data in transit. Encryption ensures that sensitive data is transmitted in an encrypted form and cannot be intercepted or modified by unauthorized parties.</p>
</li>
<li><p>Request limit: Limiting the number of API requests from a single user or IP address can prevent denial-of-service attacks and other types of abuse. Implementing TPS/RPS limiting policies can help maintain system performance and ensure that the API is available to all legitimate users.</p>
</li>
<li><p>Response limit OR pagination: APIs are dealing with larger amounts of data in their backend than ever before. To truly stand their ground in today’s digital economy, APIs must be optimized for peak efficiency. API pagination is a key strategy for making sure your APIs run smoothly and effectively.Not to return everything to the request in one shot, but divide them into multiple page/batches via a request parameter. E.g. Offset pagination is the most common used way (example: GET /items?limit=20&amp;offset=100).</p>
</li>
<li><p>Input validation and sanitization: Ensure that input data from API consumers is properly validated and sanitized to prevent attacks such as SQL injection or cross-site scripting (XSS) attacks. (this can be implemented either in the API business logic controller, or in the DB(e.g. stored procedure).</p>
</li>
<li><p>Logging and Monitoring: API usage should be monitored to detect anomalies, unusual behavior, or attacks. Logging should be enabled to track all access to APIs, including user and application details, and any errors or exceptions.</p>
</li>
<li><p>Vulnerability/Security Testing: Regular security testing and vulnerability assessments should be conducted to ensure that the API is secure against common threats and vulnerabilities.</p>
</li>
</ol>
<p>any other ways/thinking to secure the APIs?</p>
",https://stackoverflow.com/questions/75492512/how-to-secure-the-public-external-facing-apis,['api'],26,False,0,0
How to integrate OWASP ZAP into GCP Cloud Build CI/CD,"<p>I am trying to run the OWASP ZAP baseline SCAN in my Cloud Build pipeline.
<a href=""https://www.zaproxy.org/docs/docker/baseline-scan/#usage"" rel=""nofollow noreferrer"">https://www.zaproxy.org/docs/docker/baseline-scan/#usage</a>
I have found tutorials on how to do it this in Github, in Azure, and others but nothing in Cloud Build. Is there a better option for OWASP security testing?</p>
<p>This is what I have in my cloudRun.yaml file:</p>
<pre><code>steps:
- name: 'gcr.io/cloud-builders/docker'
  id: 'ZAP Proxy vulnerability scan'
  entrypoint: '/bin/sh'
  args: ['scripts/ZAP_OWASP_Run.sh','${PROJECT_ID}']
</code></pre>
<p>And this is what I have in the ZAP_OWASP_Run.sh:</p>
<p><code>docker run -v $(pwd):/zap/wrk/:rw --user root -t owasp/zap2docker-stable zap-baseline.py -t https://myWebsite.com -T 5</code></p>
<p>I had to add --user root because I was getting an error about permissions being denied.</p>
<p>This is kind of working but when I tried to add a config file to ignore certain warnings it broke again. I have had to hack this together that I started thinking I am going about this in the completely wrong way so I came to ask here.</p>
<p>Edit 1:
When I run the docker command without --user root I get the following error:</p>
<pre><code>2023-01-23 23:22:34,992 Unable to copy yaml file to /zap/wrk/zap.yaml [Errno 13] Permission denied: '/zap/wrk/zap.yaml'
</code></pre>
<p>When I try to pass in a config file:</p>
<pre><code>docker run -v $(pwd):/zap/wrk/:rw --user root -t owasp/zap2docker-stable zap-baseline.py -t https://radformation.com -T 5 -c zapAlerts.config
</code></pre>
<p>I get the following error:</p>
<pre><code>2023-01-24 00:19:09,957 Failed to load config file /zap/wrk/zapAlerts.config not enough values to unpack (expected 3, got 1)
</code></pre>
<p>EDIT 2: I got it working by first generating the config file locally and editing it, I tried to copy it from an online source originally.</p>
<p>My main question is, am I even doing this correctly? It feels very hacky. Is there a better way to ensure my website is OWASP compliant in GCP?</p>
",https://stackoverflow.com/questions/75216606/how-to-integrate-owasp-zap-into-gcp-cloud-build-ci-cd,"['docker', 'google-cloud-platform', 'google-cloud-build', 'owasp', 'zap']",186,False,1,1
