From 1c5bf07d2e4f187651cd6200f558cb5e6a8eea05 Mon Sep 17 00:00:00 2001 From: Yanming Zhou Date: Tue, 9 Sep 2025 16:42:38 +0800 Subject: [PATCH] Refine SimpleGrantedAuthority 1. Deprecate field `role` in favor of `authority` since role is specific authority. 2. Add Javadoc to state that role should be prefixed. Signed-off-by: Yanming Zhou --- .../authority/SimpleGrantedAuthority.java | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/org/springframework/security/core/authority/SimpleGrantedAuthority.java b/core/src/main/java/org/springframework/security/core/authority/SimpleGrantedAuthority.java index 72efecaf4c0..3c3cf4e29ec 100644 --- a/core/src/main/java/org/springframework/security/core/authority/SimpleGrantedAuthority.java +++ b/core/src/main/java/org/springframework/security/core/authority/SimpleGrantedAuthority.java @@ -27,21 +27,31 @@ * {@link org.springframework.security.core.Authentication Authentication} object. * * @author Luke Taylor + * @author Yanming Zhou */ public final class SimpleGrantedAuthority implements GrantedAuthority { private static final long serialVersionUID = 620L; + @Deprecated // keep it for JDK deserialization private final String role; - public SimpleGrantedAuthority(String role) { - Assert.hasText(role, "A granted authority textual representation is required"); - this.role = role; + private final String authority; + + /** + * Constructs a {@code SimpleGrantedAuthority} using the provided authority. + * @param authority The provided authority such as prefixed role + */ + public SimpleGrantedAuthority(String authority) { + Assert.hasText(authority, "A granted authority textual representation is required"); + this.authority = authority; + this.role = authority; } @Override public String getAuthority() { - return this.role; + // authority is null when deserialized from previous version + return (this.authority != null) ? this.authority : this.role; } @Override @@ -50,19 +60,19 @@ public boolean equals(Object obj) { return true; } if (obj instanceof SimpleGrantedAuthority sga) { - return this.role.equals(sga.getAuthority()); + return this.getAuthority().equals(sga.getAuthority()); } return false; } @Override public int hashCode() { - return this.role.hashCode(); + return this.getAuthority().hashCode(); } @Override public String toString() { - return this.role; + return this.getAuthority(); } }