unit-test-security-authorization
Provides patterns for unit testing Spring Security with `@PreAuthorize`, `@Secured`, `@RolesAllowed`. Validates role-based access control and authorization policies
Install / Use
npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-security-authorizationInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
SecuritySupported Platforms
Our assessment of unit-test-security-authorization
unit-test-security-authorization scores 83/100 on our quality scale, 860th of 1,115 Security skills we index.
Its SKILL.md is 6.6 KB long, well organised into 21 sections with 7 code examples: a thorough specification that gives an agent plenty to work with.
It has 353 GitHub stars, a meaningful sign that others use it.
Maintenance, license and trust
- The repository was last updated 26 days ago, so unit-test-security-authorization is actively maintained.
- It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
unit-test-security-authorization compared with similar skills
All 4 of these similar skills score higher than unit-test-security-authorization; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| unit-test-security-authorization (this skill)by giuseppe-trisciuoglio | 83 | 353 | 26d ago | SKILL.md |
| algorithmic-artby anthropics | 100 | 177.9k | 14d ago | SKILL.md |
| pptxby anthropics | 100 | 177.9k | 14d ago | SKILL.md |
| designby nextlevelbuilder | 100 | 130.2k | 15d ago | SKILL.md |
| ui-ux-pro-maxby nextlevelbuilder | 100 | 130.2k | 15d ago | SKILL.md |
Frequently asked questions
- How do I install unit-test-security-authorization?
- Run
npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-security-authorization. The install tabs above show the steps for each supported agent. - Which AI agents does unit-test-security-authorization work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is unit-test-security-authorization safe to use?
- It is MIT-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is unit-test-security-authorization still maintained?
- The repository was last updated 26 days ago, so unit-test-security-authorization is actively maintained.
Skill content
View source on GitHubname: unit-test-security-authorization
description: Provides patterns for unit testing Spring Security with @PreAuthorize, @Secured, @RolesAllowed. Validates role-based access control and authorization policies. Use when testing security configurations and access control logic.
allowed-tools: Read, Write, Bash, Glob, Grep
Unit Testing Security and Authorization
Overview
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.
When to Use
Use this skill when:
- Testing
@PreAuthorizeand@Securedmethod-level security - Testing role-based access control (RBAC)
- Testing custom permission evaluators
- Verifying access denied scenarios
- Testing authorization with authenticated principals
- Want fast authorization tests without full Spring Security context
Instructions
Follow these steps to test Spring Security authorization:
1. Set Up Security Testing Dependencies
Add spring-security-test to your test dependencies:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
2. Enable Method Security in Test Configuration
@Configuration
@EnableMethodSecurity
class TestSecurityConfig { }
3. Test with @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);
}
4. Test Custom Permission Evaluators
@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();
}
5. Validate Security is Active
If tests pass unexpectedly, add this assertion to verify security is enforced:
@Test
void shouldRejectUnauthorizedWhenSecurityEnabled() {
assertThatThrownBy(() -> service.deleteUser(1L))
.isInstanceOf(AccessDeniedException.class);
}
Quick Reference
| 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") |
Examples
Basic @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);
}
Expression-Based Security Test
@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.
Best Practices
- Use
@WithMockUserfor setting authenticated user context - Test both allow and deny cases for each security rule
- Test with different roles to verify role-based decisions
- Test expression-based security comprehensively
- Mock external dependencies (permission evaluators, etc.)
- Test anonymous access separately from authenticated access
- Use
@EnableGlobalMethodSecurityin configuration for method-level security
Common Pitfalls
- Forgetting to enable method security in test configuration
- Not testing both allow and deny scenarios
- Testing framework code instead of authorization logic
- Not handling null authentication in tests
- Mixing authentication and authorization tests unnecessarily
Constraints and Warnings
- Method security requires proxy:
@PreAuthorizeworks via proxies; direct method calls bypass security @EnableGlobalMethodSecurity: Must be enabled for@PreAuthorize,@Securedto work- Role prefix: Spring adds "ROLE_" prefix automatically; use
hasRole('ADMIN')nothasRole('ROLE_ADMIN') - Authentication context: Security context is thread-local; be careful with async tests
@WithMockUserlimitations: Creates a simple Authentication; complex auth scenarios need custom setup- SpEL expressions: Complex SpEL in
@PreAuthorizecan be difficult to debug; test thoroughly - Performance impact: Method security adds overhead; consider security at layer boundaries
References
Setup and Configuration
- references/setup.md - Maven/Gradle dependencies and security configuration
Testing Patterns
- references/basic-testing.md - Basic patterns for
@PreAuthorize,@Secured, MockMvc testing, and parameterized tests
Advanced Topics
- references/advanced-authorization.md - Expression-based authorization, custom permission evaluators, SpEL expressions
Complete Examples
- references/complete-examples.md - Before/after examples showing transition from manual to declarative security
Related Skills
algorithmic-art
177.9kCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems.
pptx
177.9kUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an em…
design
130.2kComprehensive design skill: brand identity, design tokens, UI styling, logo generation (55 styles, Gemini, Atlas Cloud, or MuAPI AI), corporate identity program (50 deliverables, CIP mockups), HTML presentations (Chart.js), banner design (22 styles, social/ads/web/print), icon design (15 styles, SVG…
ui-ux-pro-max
130.2kUI/UX design intelligence for web, mobile, and desktop. This skill should be used when designing, building, reviewing, or fixing interfaces, including pages, components, design systems, accessibility, interaction, responsive layout, typography, color, charts, and stack-specific UI implementation.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
