Unit testing patterns for Spring Security authorization annotations and role-based access control.
Works with
Covers @PreAuthorize , @Secured , and @RolesAllowed method-level security with @WithMockUser test fixtures
Includes role-based access control (RBAC), expression-based authorization, and custom PermissionEvaluator testing
Provides MockMvc patterns for testing secured REST endpoints and parameterized role testing strategies
Demonstrates both allow and deny scenarios, owner-based access
AI-first code editor with Composer
Before installing skills in Cursor, ensure your development environment meets these requirements:
node --versionunit-test-security-authorizationExecute the skills CLI command in your project's root directory to begin installation:
Fetches unit-test-security-authorization from giuseppe-trisciuoglio/developer-kit and configures it for Cursor.
The CLI shows a list of agents. Use arrow keys and space to select Cursor:
Confirm successful installation by checking the skill directory location:
Restart Cursor to activate unit-test-security-authorization. Access via /unit-test-security-authorization in your agent's command palette.
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your environment. Always review source, verify the publisher, and test in isolation before production.
Submit your Claude Code skill and start earning
Automate repetitive workflows and reduce manual effort
Example
Generate reports, summarize documents, draft communications
Save 3-5 hours per week on routine tasks
Learn new skills, understand complex topics, get expert guidance
Example
Explain concepts, provide examples, suggest learning resources
Accelerate learning and skill development by 2x
Enhance output quality through reviews, suggestions, and refinements
Example
Review drafts, suggest improvements, catch errors
Improve work quality by 30-40% with less effort
0
total installs
0
this week
194
GitHub stars
0
upvotes
Run in your terminal
0
installs
0
this week
194
stars
This skill provides patterns for unit testing Spring Security authorization logic using @PreAuthorize, @Secured, @RolesAllowed, and custom permission evaluators. It covers testing role-based access control (RBAC), expression-based authorization, custom permission evaluators, and verifying access denied scenarios without full Spring Security context.
Use this skill when:
@PreAuthorize and @Secured method-level securityFollow these steps to test Spring Security authorization:
Add spring-security-test to your test dependencies:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
@Configuration
@EnableMethodSecurity
class TestSecurityConfig { }
@WithMockUser@Test
@WithMockUser(roles = "ADMIN")
void shouldAllowAdminAccess() {
assertThatCode(() -> service.deleteUser(1L))
.doesNotThrowAnyException();
}
@Test
@WithMockUser(roles = "USER")
void shouldDenyUserAccess() {
assertThatThrownBy(() -> service.deleteUser(1L))
.isInstanceOf(AccessDeniedException.class);
}
@Test
void shouldGrantPermissionToOwner() {
Authentication auth = new UsernamePasswordAuthenticationToken(
"alice", null, List.of(new SimpleGrantedAuthority("ROLE_USER"))
);
Document doc = new Document(1L, "Test", new User("alice"));
boolean result = evaluator.hasPermission(auth, doc, "WRITE");
assertThat(result).isTrue();
}
If tests pass unexpectedly, add this assertion to verify security is enforced:
@Test
void shouldRejectUnauthorizedWhenSecurityEnabled() {
assertThatThrownBy(() -> service.deleteUser(1L))
.isInstanceOf(AccessDeniedException.class);
}
| Annotation | Description | Example |
|---|---|---|
@PreAuthorize |
Pre-invocation authorization | @PreAuthorize("hasRole('ADMIN')") |
@PostAuthorize |
Post-invocation authorization | @PostAuthorize("returnObject.owner == authentication.name") |
@Secured |
Simple role-based security | @Secured("ROLE_ADMIN") |
@RolesAllowed |
JSR-250 standard | @RolesAllowed({"ADMIN", "MANAGER"}) |
@WithMockUser |
Test annotation | @WithMockUser(roles = "ADMIN") |
@PreAuthorize Test@Service
public class UserService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long userId) {
// delete logic
}
}
// Test
@Test
@WithMockUser(roles = "ADMIN")
void shouldAllowAdminToDeleteUser() {
assertThatCode(() -> service.deleteUser(1L))
.doesNotThrowAnyException();
}
@Test
@WithMockUser(roles = "USER")
void shouldDenyUserFromDeletingUser() {
assertThatThrownBy(() -> service.deleteUser(1L))
.isInstanceOf(AccessDeniedException.class);
}
@PreAuthorize("#userId == authentication.principal.id")
public UserProfile getUserProfile(Long userId) {
// get profile
}
// For custom principal properties, use @WithUserDetails with a custom UserDetailsService
@Test
@WithUserDetails("alice")
void shouldAllowUserToAccessOwnProfile() {
assertThatCode(() -> service.getUserProfile(1L))
.doesNotThrowAnyException();
}
Validation tip: If a security test passes unexpectedly, verify that
@EnableMethodSecurityis active on the test configuration — a missing annotation causes all@PreAuthorizechecks to be bypassed silently.
See references/basic-testing.md for more basic patterns and references/advanced-authorization.md for complex expressions and custom evaluators.
@WithMockUser for setting authenticated user context@EnableGlobalMethodSecurity in configuration for method-level security@PreAuthorize works via proxies; direct method calls bypass security@EnableGlobalMethodSecurity: Must be enabled for @PreAuthorize, @Secured to workhasRole('ADMIN') not hasRole('ROLE_ADMIN')@WithMockUser limitations: Creates a simple Authentication; complex auth scenarios need custom setup@PreAuthorize can be difficult to debug; test thoroughly@PreAuthorize, @Secured, MockMvc testing, and parameterized testsPrerequisites
Time Estimate
15-45 minutes depending on use case complexity
Steps
Common Pitfalls
✓ Do
✗ Don't
💡 Pro Tips
✓ Use when
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
✗ Avoid when
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
giuseppe-trisciuoglio/developer-kit
giuseppe-trisciuoglio/developer-kit
giuseppe-trisciuoglio/developer-kit
giuseppe-trisciuoglio/developer-kit
cexll/myclaude
github/awesome-copilot
unit-test-security-authorization fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
We added unit-test-security-authorization from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
Keeps context tight: unit-test-security-authorization is the kind of skill you can hand to a new teammate without a long onboarding doc.
unit-test-security-authorization fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
Registry listing for unit-test-security-authorization matched our evaluation — installs cleanly and behaves as described in the markdown.
unit-test-security-authorization is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
Useful defaults in unit-test-security-authorization — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
unit-test-security-authorization has been reliable in day-to-day use. Documentation quality is above average for community skills.
I recommend unit-test-security-authorization for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
unit-test-security-authorization is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
showing 1-10 of 62