Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3524

Spring Security 6.3 – What’s New

$
0
0

1. Introduction

Spring Security version 6.3 has introduced a range of security enhancements in the framework.

In this tutorial, we’ll discuss some of the most notable features, highlighting their benefits and usage.

2. Passive JDK Serialization Support

Spring Security 6.3 included passive JDK serialization support. However, before we discuss this further, let’s understand the problem and issues surrounding it.

2.1. Spring Security Serialization Design

Before version 6.3, Spring Security had a strict policy regarding serialization and deserialization of its classes across different versions through JDK serialization. This restriction was a deliberate design decision by the framework to ensure security and stability. The rationale was to prevent incompatibilities and security vulnerabilities from deserializing objects serialized in one version using a different version of Spring Security.

One key aspect of this design is the usage of a global serialVersionUID for the entire Spring Security project. In Java, the serialization and deserialization process uses a unique identifier serialVersionUID to verify that a loaded class corresponds exactly to a serialized object.

By maintaining a global serialVersionUID unique to each release version of Spring Security, the framework ensures that serialized objects from one version cannot be deserialized using another version. This approach effectively creates a version barrier, preventing the deserialization of objects with mismatched serialVersionUID values.

For example, the SecurityContextImpl class in Spring Security represents security context information. The serialized version of this class includes the serialVersionUID specific to that version. When attempting to deserialize this object in a different version of Spring Security, the serialVersionUID mismatch prevents the process from succeeding.

2.2. Challenges Arising from the Serialization Design

While prioritizing enhanced security, this design policy also introduces several challenges. Developers commonly integrate Spring Security with other Spring libraries, such as Spring Session, to manage user login sessions. These sessions encompass crucial user authentication and security context information, typically implemented through Spring Security classes. Furthermore, to optimize user experience and enhance application scalability, developers often store this session data across various persistent storage solutions, including databases.

The following are some of the challenges that arise due to the serialization design. Upgrading applications through the Canary release process can lead to an issue if the Spring Security version changes. In such cases, the persisted session information cannot be deserialized, potentially necessitating users to re-login.

Another issue arises in application architectures utilizing Remote Method Invocation (RMI) with Spring Security. For instance, if the client application employs Spring Security classes in a remote method call, it must serialize them on the client side and deserialize them on the other side. If both applications do not share the same Spring Security version, this invocation fails, resulting in an InvalidClassException exception.

2.3. Workarounds

The typical workarounds for this issue are as follows. We can use a different serialization library other than JDK Serialization, such as Jackson Serialization. With this, instead of serializing the Spring Security class, we obtain a JSON representation of the required details and serialize it with Jackson.

Another option is to extend the required Spring Security class, such as Authentication, and explicitly implement custom serialization support through the readObject and writeObject methods.

2.4. Serialization Changes in Spring Security 6.3

With version 6.3, class serialization undergoes a compatibility check with the preceding minor version. This ensures that upgrading to newer versions allows the deserialization of Spring Security classes seamlessly.

3. Authorization

Spring Security 6.3 has introduced a few notable changes in the Spring Security Authorization. Let us explore these in this section.

3.1. Annotation Parameters

Spring Security’s method security supports meta-annotations. We can take an annotation and improve it’s readability based on the application’s use case. For instance, we can simplify the @PreAuthorize(“hasRole(‘USER’)”) to the following:

@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('USER')")
public @interface IsUser {
    String[] value();
}

Next, we can use this @IsUser annotation in the business code:

@Service
public class MessageService {
    @IsUser
    public Message readMessage() {
        return "Message";
    }
}

Let’s assume we have another role, ADMIN. We can create an annotation named @IsAdmin for this role. However, this would be redundant. It would be more appropriate to use this meta-annotation as a template and include the role as an annotation parameter. Spring Security 6.3 introduces the ability to define such meta-annotations. Let us demonstrate this with a concrete example:

To template a meta-annotation, first, we need to define a bean PrePostTemplateDefaults:

@Bean
PrePostTemplateDefaults prePostTemplateDefaults() {
    return new PrePostTemplateDefaults();
}

This bean definition is required for the template resolution.

Next, we’ll define a meta-annotation @CustomHasAnyRole for the @PreAuthorize annotation that can accept both USER and ADMIN roles:

@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAnyRole({value})")
public @interface CustomHasAnyRole {
    String[] value();
}

We can use this meta-annotation by supplying the roles:

@Service
public class MessageService {
    private final List<Message> messages;
    public MessageService() {
        messages = new ArrayList<>();
        messages.add(new Message(1, "Message 1"));
    }
    
    @CustomHasAnyRole({"'USER'", "'ADMIN'"})
    public Message readMessage(Integer id) {
        return messages.get(0);
    }
    @CustomHasAnyRole("'ADMIN'")
    public String writeMessage(Message message) {
        return "Message Written";
    }
    
    @CustomHasAnyRole({"'ADMIN'"})
    public String deleteMessage(Integer id) {
        return "Message Deleted";
    }
}

In the above example, we supplied the role values – USER and ADMIN as the annotation parameter.

3.2. Securing Return Values

Another powerful new feature in Spring Security 6.3 is the ability to secure domain objects using the @AuthorizeReturnObject annotation. This enhancement allows for more granular security by enabling authorization checks on the objects returned by methods, ensuring that only authorized users can access specific domain objects.

Let us demonstrate this with an example. Let’s say we have the following Account class with the iban and balance fields. The requirement is that only users with read authority can retrieve the account balance.

public class Account {
    private String iban;
    private Double balance;
    // Constructor
    public String getIban() {
        return iban;
    }
    @PreAuthorize("hasAuthority('read')")
    public Double getBalance() {
        return balance;
    }
}

Next, let us define the AccountService class, which returns an account instance:

@Service
public class AccountService {
    @AuthorizeReturnObject
    public Optional<Account> getAccountByIban(String iban) {
        return Optional.of(new Account("XX1234567809", 2345.6));
    }
}

In the above snippet, we have used the @AuthorizeReturnObject annotation. Spring security ensures that the Account instance can only be accessed by the user with read authority.

3.3. Error Handling

In the section above, we discussed using the @AuthorizeReturnObject annotation to secure the domain objects. Once enabled, the unauthorized access results in an AccessDeniedException. Spring Security 6.3 provides the MethodAuthorizationDeniedHandler interface to handle authorization failures.

Let us demonstrate this with an example. Let us extend the example in section 3.2 and secure the IBAN with the read authority. However, we intend to provide a masked value instead of returning an AccessDeniedException for any unauthorized access.

Let us define an implementation of the MethodAuthorizationDeniedHandler interface:

@Component
public class MaskMethodAuthorizationDeniedHandler implements MethodAuthorizationDeniedHandler  {
    @Override
    public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
        return "****";
    }
}

In the above snippet, we provided a masked value if there is an AccessDeniedException. This handler class can be used in the getIban() method, as shown below:

@PreAuthorize("hasAuthority('read')")
@HandleAuthorizationDenied(handlerClass=MaskMethodAuthorizationDeniedHandler.class)
public String getIban() {
    return iban;
}

4. Compromised Password Checking

Spring Security 6.3 provides an implementation for compromised password checks. This implementation checks a provided password against a compromised password database (pwnedpasswords.com). Therefore, applications can verify the user-provided password at registration time. The following code snippets demonstrate the usage.

First, define a bean definition of HaveIBeenPwnedRestApiPasswordChecker class:

@Bean
public HaveIBeenPwnedRestApiPasswordChecker passwordChecker() {
    return new HaveIBeenPwnedRestApiPasswordChecker();
}

Next, use this implementation to check the user-provided password:

@RestController
@RequestMapping("/register")
public class RegistrationController {
    private final HaveIBeenPwnedRestApiPasswordChecker haveIBeenPwnedRestApiPasswordChecker;
    @Autowired
    public RegistrationController(HaveIBeenPwnedRestApiPasswordChecker haveIBeenPwnedRestApiPasswordChecker) {
        this.haveIBeenPwnedRestApiPasswordChecker = haveIBeenPwnedRestApiPasswordChecker;
    }
    @PostMapping
    public String register(@RequestParam String username, @RequestParam String password) {
        CompromisedPasswordDecision compromisedPasswordDecision = haveIBeenPwnedRestApiPasswordChecker.checkPassword(password);
        if (compromisedPasswordDecision.isCompromised()) {
	    throw new IllegalArgumentException("Compromised Password.");
	}
        // ...
        return "User registered successfully";
    }
}

5. OAuth 2.0 Token Exchange Grant

Spring Security 6.3 also introduced support for the OAuth 2.0 Token Exchange (RFC 8693) grant, allowing clients to exchange tokens while retaining the user’s identity. This feature enables scenarios like impersonation, where a resource server can act as a client to obtain new tokens. Let us elaborate on this with an example.

Let’s assume we have a resource server named loan-service, which provides various APIs for loan accounts. This service is secured, and clients need to supply an access token that must have the audience (aud claim) of the loan service.

Let’s now imagine that loan-service needs to invoke another resource service loan-product-service which exposes details for loan products. The loan-product-service is also secure and requires tokens that must have the audience of the loan-product-service. Since the audience is different in these two services, the token for loan service can’t be used for loan-product-service.

In this case, the resource server, loan-service should become a client and exchange the existing token for a new token for loan-product-service that retains the the original token identity.

Spring Security 6.3 provides a new implementation of the OAuth2AuthorizedClientProvider class named TokenExchangeOAuth2AuthorizedClientProvider for the token-exchange grant.

6. Conclusion

In this article, we discussed various new features introduced in Spring Security 6.3.

The notable changes are enhancement to the authorization framework, passive JDK serialization support, and OAuth 2.0 Token Exchange support.

The source code is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 3524

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>