SonarSource/sonarqube · error · UnauthorizedException

UserSession not found in authentication principal

Error message

UserSession not found in authentication principal

What it means

UnauthorizedException thrown by SecurityContextBackedUserSession.delegate() when an Authentication exists but its principal is not a SonarUserDetails instance, so no UserSession can be extracted. This indicates an unexpected principal type in the security context — an internal wiring/auth-filter problem rather than user error.

Solutions

  1. Ensure the authentication filter populates SonarUserDetails as the principal
  2. Remove or fix custom security filters/plugins replacing the principal
  3. Align all SonarQube modules to the same version (redeploy webapp)
  4. Log the principal's concrete class to diagnose which component set it
Defensive patterns

Strategy: try-catch

Try / catch

try {
    session = securityContextBackedUserSession.getLogin();
} catch (UnauthorizedException e) {
    // principal wiring problem: inspect SecurityContext authentication principal type
}

Prevention

When it happens

Trigger: An authenticated Authentication whose getPrincipal() is not SonarUserDetails reaches a call that resolves the UserSession — e.g. custom authentication filters, alternate token auth paths, or version mismatch between security modules.

Common situations: Custom Spring Security integrations setting their own principal, partially upgraded installations with mismatched security components, plugins injecting custom Authentication objects.

Understand the failure class

Related errors


AI-assisted analysis of SonarSource/sonarqube@184c821202 (2026-09-09). Data as JSON: /api/errors/c259f977c7740687. Report an issue: GitHub.

Appendix: source

Thrown at server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/security/SecurityContextBackedUserSession.java:69

  /**
   * Get the UserSession from SecurityContext.
   * This extracts the actual UserSession stored in the SonarUserDetails principal.
   */
  private static UserSession delegate() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
      throw new UnauthorizedException("Authentication is required");
    }

    // Extract UserSession from SonarUserDetails principal
    Object principal = authentication.getPrincipal();
    if (principal instanceof SonarUserDetails sonarUserDetails) {
      return sonarUserDetails.getUserSession();
    }

    throw new UnauthorizedException("UserSession not found in authentication principal");
  }

  @Override
  @CheckForNull
  public String getLogin() {
    return delegate().getLogin();
  }

  @Override
  @CheckForNull
  public String getUuid() {
    return delegate().getUuid();
  }

  @Override
  @CheckForNull
  public String getName() {
    return delegate().getName();

View on GitHub (pinned to 184c821202)