Search code examples
spring-bootspring-securityspring-authorization-server

Is there a way to add custom attributes to OAuth2Authorizations in Spring's Authorization Server?


I'm using spring-security-oauth2-authorization-server-1.1.1 with the JdbcOAuth2AuthorizationService to persist OAuth2Authorization instances to a database. I would like to include additional details about the request in the database. In particular I'm looking to capture the User-Agent HTTP header and the request's IP address.

Looking at OAuth2Authorization and OAuth2Authorization.Builder, there's an attribute Map that can be populated with extra details like this, but I'm not sure if this is an appropriate use the attributes feature, nor do I see a way to hook into spring-security to capture details from the HttpServletRequest.

Thanks in advance!


Solution

  • There isn't currently a direct way to customize an OAuth2Authorization before it is saved. However, you can do this with delegation by implementing a custom OAuth2AuthorizationService. For example:

    @Component
    public class DecoratingOAuth2AuthorizationService implements OAuth2AuthorizationService {
        private final OAuth2AuthorizationService delegate;
    
        public DecoratingOAuth2AuthorizationService(
                JdbcOperations jdbcTemplate,
                RegisteredClientRepository registeredClientRepository) {
            this.delegate = new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
        }
    
        @Override
        public void save(OAuth2Authorization authorization) {
            OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
                    // ... add attributes
                    .build();
            this.delegate.save(updatedAuthorization);
        }
    
        // ...
    }
    

    Note: The HttpServletRequest is available via ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().