code: public Authentication build(final UserProfile profile,
                                  final OAuthRegisteredService registeredService,
                                  final J2EContext context,
                                  final Service service) {
  
          val profileAttributes = CoreAuthenticationUtils.convertAttributeValuesToMultiValuedObjects(profile.getAttributes());
          val newPrincipal = this.principalFactory.createPrincipal(profile.getId(), profileAttributes);
          LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
  
          val authenticator = profile.getClass().getCanonicalName();
          val metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
          val handlerResult = new DefaultAuthenticationHandlerExecutionResult(authenticator, metadata, newPrincipal, new ArrayList<>());
          val scopes = CollectionUtils.toCollection(context.getRequest().getParameterValues(OAuth20Constants.SCOPE));
  
          val state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.STATE), StringUtils.EMPTY);
          val nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.NONCE), StringUtils.EMPTY);
          LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce);
  
          /*
           * pac4j UserProfile.getPermissions() and getRoles() returns UnmodifiableSet which Jackson Serializer
           * happily serializes to json but is unable to deserialize.
           * We have to transform those to HashSet to avoid such a problem
           */
          return DefaultAuthenticationBuilder.newInstance()
              .addAttribute("permissions", new LinkedHashSet<>(profile.getPermissions()))
              .addAttribute("roles", new LinkedHashSet<>(profile.getRoles()))
              .addAttribute("scopes", scopes)
              .addAttribute(OAuth20Constants.STATE, state)
              .addAttribute(OAuth20Constants.NONCE, nonce)
              .addAttribute(OAuth20Constants.CLIENT_ID, registeredService.getClientId())
              .addCredential(metadata)
              .setPrincipal(newPrincipal)
              .setAuthenticationDate(ZonedDateTime.now(ZoneOffset.UTC))
              .addSuccess(profile.getClass().getCanonicalName(), handlerResult)
              .build();
      }
docs: Create an authentication from a user profile.
  
  @param profile           the given user profile
  @param registeredService the registered service
  @param context           the context
  @param service           the service
  @return the built authentication