Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
giuseppe-trisciuoglio avatar

Unit Test Security Authorization

  • 1.6k installs
  • 311 repo stars
  • Updated June 22, 2026
  • giuseppe-trisciuoglio/developer-kit

Patterns and techniques for unit testing Spring Security authorization annotations and custom permission evaluators to verify role-based access control is correctly enforced.

About

This skill provides patterns for unit testing Spring Security authorization annotations (@PreAuthorize, @Secured, @RolesAllowed) and custom permission evaluators. Developers use it when validating role-based access control (RBAC), expression-based authorization, and access denied scenarios without full Spring Security context. Key workflows include setting up spring-security-test, enabling method security in test configuration, using @WithMockUser to simulate authenticated users, testing both allow and deny cases, and validating custom permission evaluators. The skill emphasizes testing both positive and negative scenarios, verifying that security annotations are active, and avoiding common pitfalls like forgetting @EnableMethodSecurity or bypassing security via direct method calls.

  • Test @PreAuthorize and @Secured method-level security with @WithMockUser annotation to mock authenticated principals
  • Validate role-based access control (RBAC) by testing both allow and deny scenarios for each security rule
  • Test custom permission evaluators by directly instantiating Authentication objects and calling hasPermission logic
  • Verify security is enforced by asserting AccessDeniedException is thrown for unauthorized access attempts
  • Enable method security in test configuration with @EnableMethodSecurity to ensure @PreAuthorize checks are not silently

Unit Test Security Authorization by the numbers

  • 1,648 all-time installs (skills.sh)
  • +56 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #439 of 2,184 Testing & QA skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

unit-test-security-authorization capabilities & compatibility

Capabilities
generate unit tests for @preauthorize and @secur · create test cases for role based access control · test custom permission evaluators with mocked au · verify accessdeniedexception is thrown for unaut · set up spring security test configuration with m · parameterize tests to validate multiple roles an
Works with
github · gitlab · bitbucket · jira
Use cases
testing · security audit · code review
Platforms
macOS · Windows · Linux
Runs
Runs locally
Pricing
Free
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-security-authorization

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1.6k
repo stars311
Security audit3 / 3 scanners passed
Last updatedJune 22, 2026
Repositorygiuseppe-trisciuoglio/developer-kit

What it does

Unit test Spring Security authorization logic with @PreAuthorize, @Secured, and custom permission evaluators to validate role-based access control.

Who is it for?

Testing Spring Security method-level authorization, validating RBAC policies, verifying custom permission evaluators, confirming access denied scenarios.

Skip if: Integration testing of full Spring Security context, testing authentication (login/logout), testing web layer security via MockMvc HTTP calls.

When should I use this skill?

Building authorization-protected service methods, implementing role-based access control, creating custom permission evaluators, validating security expressions.

What you get

Developers can write comprehensive unit tests for authorization logic that validate role-based decisions, expression-based security, custom permissions, and access denied scenarios.

  • Unit test classes for authorization logic
  • Test configuration with @EnableMethodSecurity
  • Parameterized tests for multiple roles

By the numbers

  • Four main authorization annotations covered: @PreAuthorize, @PostAuthorize, @Secured, @RolesAllowed
  • Three common testing pitfalls identified: forgetting @EnableMethodSecurity, not testing deny cases, testing framework in
  • Seven best practices documented including use of @WithMockUser, testing both allow/deny, mocking dependencies

Files

SKILL.mdMarkdownGitHub ↗

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 @PreAuthorize and @Secured method-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

AnnotationDescriptionExample
@PreAuthorizePre-invocation authorization@PreAuthorize("hasRole('ADMIN')")
@PostAuthorizePost-invocation authorization@PostAuthorize("returnObject.owner == authentication.name")
@SecuredSimple role-based security@Secured("ROLE_ADMIN")
@RolesAllowedJSR-250 standard@RolesAllowed({"ADMIN", "MANAGER"})
@WithMockUserTest 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 @EnableMethodSecurity is active on the test configuration — a missing annotation causes all @PreAuthorize checks 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

1. Use `@WithMockUser` for setting authenticated user context 2. Test both allow and deny cases for each security rule 3. Test with different roles to verify role-based decisions 4. Test expression-based security comprehensively 5. Mock external dependencies (permission evaluators, etc.) 6. Test anonymous access separately from authenticated access 7. Use `@EnableGlobalMethodSecurity` in 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: @PreAuthorize works via proxies; direct method calls bypass security
  • `@EnableGlobalMethodSecurity`: Must be enabled for @PreAuthorize, @Secured to work
  • Role prefix: Spring adds "ROLE_" prefix automatically; use hasRole('ADMIN') not hasRole('ROLE_ADMIN')
  • Authentication context: Security context is thread-local; be careful with async tests
  • `@WithMockUser` limitations: Creates a simple Authentication; complex auth scenarios need custom setup
  • SpEL expressions: Complex SpEL in @PreAuthorize can be difficult to debug; test thoroughly
  • Performance impact: Method security adds overhead; consider security at layer boundaries

References

Setup and Configuration

  • [references/setup.md](references/setup.md) - Maven/Gradle dependencies and security configuration

Testing Patterns

  • [references/basic-testing.md](references/basic-testing.md) - Basic patterns for @PreAuthorize, @Secured, MockMvc testing, and parameterized tests

Advanced Topics

  • [references/advanced-authorization.md](references/advanced-authorization.md) - Expression-based authorization, custom permission evaluators, SpEL expressions

Complete Examples

  • [references/complete-examples.md](references/complete-examples.md) - Before/after examples showing transition from manual to declarative security

Related skills

Forks & variants (1)

Unit Test Security Authorization has 1 known copy in the catalog totaling 20 installs. They canonicalize to this original listing.

How it compares

Use this skill for method-level Spring Security expressions; use integration-test skills when authorization must be validated across full HTTP flows.

FAQ

What dependency do I need to add for Spring Security testing?

Add spring-security-test to test dependencies: <artifactId>spring-security-test</artifactId> with scope=test. This provides @WithMockUser and other testing utilities.

Why do my @PreAuthorize tests pass when they should fail?

Method security requires @EnableMethodSecurity in test configuration. Without it, @PreAuthorize checks are silently bypassed. Verify this annotation is on your TestSecurityConfig class.

How do I test both allow and deny scenarios?

Write two tests for each rule: one with @WithMockUser(roles = 'ADMIN') that asserts no exception, and one with @WithMockUser(roles = 'USER') that asserts AccessDeniedException is thrown.

Is Unit Test Security Authorization safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Testing & QAauditappsec

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.